Java Video Tutorial 32

Java Character StreamsIn this part of my Java Video Tutorial, I completely cover how to both write to and read character streams from files.

I explain all of the following: PrintWriter, BufferedWriter, FileWriter, BufferedReader, FileReader, common file exceptions and much more.

All of the code follows the video. It is heavily commented and will help you build your Java code repository while helping you to learn Java better.

If you like videos like this share it

Code from the Video

import java.io.*;

// A character stream is just a series of characters
// Important information is normally separated by a comma,
// space, or tab.

public class Lesson32{
	
	public static void main(String[] args){
		
		// Create an array of type Customer
		
		Customer[] customers = getCustomers();
		
		// PrintWriter is used to write characters to a file in this situation
		
		PrintWriter custOutput = createFile("/Users/derekbanas/Documents/workspace3/Java Code/src/customers.txt");
		
		// Enhanced for loop for arrays
		// Cycles through all of the people in the customers array
		
		for(Customer person : customers){
			
			createCustomers(person, custOutput);
			
		}
		
		// Closes the connection to the PrintWriter
		
		custOutput.close();
		
		getFileInfo();
		
	}
	
	// class that defines all the fields for my customers
	
	private static class Customer{
		
		public String firstName, lastName;
		public int custAge;
		
		// constructor that's called when a customer is made
		
		public Customer(String firstName, String lastName, int custAge){
			
			this.firstName = firstName;
			this.lastName = lastName;
			this.custAge = custAge;
			
		}
		
	}
	
	// Creates an array of Customer Objects
	
	private static Customer[] getCustomers(){
		
		Customer[] customers = new Customer[5];
		
		customers[0] = new Customer("John", "Smith", 21);
		customers[1] = new Customer("Sally", "Smith", 30);
		customers[2] = new Customer("Paul", "Ryan", 21);
		customers[3] = new Customer("Mark", "Jacobs", 21);
		customers[4] = new Customer("Steve", "Nash", 21);
		
		return customers;
		
	}
	
	// Create the file and the PrintWriter that will write to the file
	
	private static PrintWriter createFile(String fileName){
		
		try{
			
			// Creates a File object that allows you to work with files on the hardrive
			
			File listOfNames = new File(fileName);
			
			// FileWriter is used to write streams of characters to a file
			// BufferedWriter gathers a bunch of characters and then writes
			// them all at one time (Speeds up the Program)
			// PrintWriter is used to write characters to the console, file
	
			PrintWriter infoToWrite = new PrintWriter(
			new BufferedWriter(
					new FileWriter(listOfNames)));
			return infoToWrite;
		}
	
		// You have to catch this when you call FileWriter
		
		catch(IOException e){
		
			System.out.println("An I/O Error Occurred");
			
			// Closes the program
			
			System.exit(0);
		
		}
		return null;
		
	}
	
	// Create a string with the customer info and write it to the file
	
	private static void createCustomers(Customer customer, PrintWriter custOutput){
		
		// Create the String that contains the customer info
		
		String custInfo = customer.firstName + " " + customer.lastName + " ";
		custInfo += Integer.toString(customer.custAge);
		
		// Writes the string to the file
		
		custOutput.println(custInfo);
		
	}
	
	// Read info from the file and write it to the screen
	
	private static void getFileInfo(){
		
		System.out.println("Info Written to File\n");
		
		// Open a new connection to the file
		
		File listOfNames = new File("/Users/derekbanas/Documents/workspace3/Java Code/src/customers.txt");
		
		try {
			
			// FileReader reads character files
			// BufferedReader reads as many characters as possible
			
			BufferedReader getInfo = new BufferedReader(
					new FileReader(listOfNames));
			
			// Reads a whole line from the file and saves it in a String
			
			String custInfo = getInfo.readLine();
			
			// readLine returns null when the end of the file is reached
			
			while(custInfo != null){
				
				// System.out.println(custInfo);
				
				// Break lines into pieces
				
				String[] indivCustData = custInfo.split(" ");
				
				// Convert the String into an integer with parseInt
				
				int custAge = Integer.parseInt(indivCustData[2]);
				
				System.out.print("Customer " + indivCustData[0] + " is " + custAge +"\n");
				
				custInfo = getInfo.readLine();
				
			}
			
			
			
		} 
		
		// Can be thrown by FileReader
		
		catch (FileNotFoundException e) {
			
			System.out.println("Couldn't Find the File");
			System.exit(0);
		}
		
		catch(IOException e){
			
			System.out.println("An I/O Error Occurred");
			System.exit(0);
		
		}
		
	}
	
	
}

62 Responses to “Java Video Tutorial 32”

  1. samran says:

    please make us a tutorial about JTable and connection with a database

    thank you

    • admin says:

      Sure I’ll do that. What specifically would you like to see in the tutorial? I’m giving you the power to define the structure of the tutorial as long as you don’t go to crazy πŸ™‚

  2. mr.roshik says:

    hi bro im unable to understand about proper use of html param and span tag, can u help me?

    • admin says:

      A span is like a div, but it doesn’t force a line break to occur after it. While divs normally surround large pieces of information, a span normally surrounds a small line.

      param is used to set a value to a param / field / variable that is used by an object like videos, audio clips, Flash, etc. Objects are normally handled by a plugin in the browser.

      Does that make sense?

      • Anonymous says:

        thank you very much bro.span is clear to me now, but im still little bit confused about param, i chked w3schools but i didnt get a clear example, however you are very friendly , wish u all the best, take care

  3. Punit says:

    nice video…
    thank you..

  4. samran says:

    thank you so much to give me the power to define the structor of the tutorial , i think it could be good tutorial if you teach us how creat a a dynamic table connected to a database
    with a hover effect, and some checkBoxes to modify or delete the selectedRow, and i think it will be wonderful if you we learn how to creat tables like we see in excel tables of microsoft office
    with these tools of calculating dynamic data, add, division ect.. and the golbal sum of a selectedRows..

    you gave me the power to be the king of that day, i hope it wont be unbearable kingdom.
    thank you sooo much.

    • admin says:

      Well I could do that, but excel files are saved as comma separated lists and not in a database. I could display database information in a JTable though it wouldn’t be a common practice especially for a spreadsheet like application. I’ll see what I can do. I definitely will cover databases and JTables. Thanks for the idea

  5. mr.roshik says:

    pls

  6. Punit says:

    please, also do some tutorial on how to use xml in java, and java networking, rmi and corba.
    and if possible, make one video for how to use html in core java..
    thank you.

    • admin says:

      Here is what I have planned to cover in this tutorial:

      1. More GUI components
      2. Files
      3. Streams
      4. Java 2D
      5. Recursion
      6. Data Structures
      7. Applets & Servlets
      8. Networking
      9. Databases (MySQL) JDBC
      10. Server Faces
      11. Web Services (SOAP, JSON)
      12. XML
      13. Review of the differences between 1.6 & 1.7 (path, nio, etc.)

      I haven’t decided if I’ll cover OpenGL, Android, Game Programming yet? I’m not covering hibernate and corba is kind of a stretch. We’ll see what happens there? It will be the most comprehensive Java tutorial ever made by the end

      • Punit says:

        after looking the entire contents, i only want to say, just do it man, i m just curious to learn..;-)
        please add more an more, and please cover android also, it’s on boom right now..
        thank you..

        • admin says:

          I’ll more than likely cover Android. I have been working on a toddler game because I never found one that did everything I wanted. It’s just such a long process. The illustration work that goes into it is quite complicated. I may have to do something on drawing as well? We’ll see what happens. I just don’t want to put a tutorial out unless I really like it

          • Punit says:

            the game seems something very interesting, anyways if it is easily possible for you, do this as an illustration process.

            Thank you..

            • Punit says:

              also i just want to know one more thing, as you said about “toddler game”, it’s a kind of game which can be played online, isn’t it??
              i mean, we just attach that game with our site, and anyone can play that game, something like this??

              • admin says:

                By toddler game I mean for young children. I have noticed many flaws in games and I’ve been working on a came that will help children learn everything they need to know. It is a great learning aid because each part of the app will focus on different techniques any app would require.

                I’ll start making it as soon as I get time. It will be a major undertaking.

  7. Punit says:

    and also please do some tutorials for nio..

  8. mr.roshik says:

    hi bro, in wordpress we use header, footer even sidebar as a constant file. i mean we dont need to copy paste whole coding in every page, is it possible in static web site? i want to separate header and footer and then i want to use them in every page by linking. i checked your tutorial “how to layout a website part 1 to 5” it is really great. thank you

  9. mr.roshik says:

    How can i reply in your post with my avatar ? your site is rich enough, why not u make a forum for us ? Arent you interested about registration system for your site? i think javascript is a complicated language though we can make nice slider by javascript. so im interested to learn implementation of it. PLEASE suggest me about that πŸ˜€

    • admin says:

      I made a couple slider tutorials with JavaScript. I have tons of stuff here. It is just hard to find all of it. Many of my best tutorials are on this page What is New Think Tank.

      I never made a full forum here because they are kind of hard to manage security wise. I guess I could create a phpBB forum? If you think people would like that I’ll do it.

  10. Punit says:

    thank you very much..
    please start it as soon as possible…
    and if possible, please let me know, any source for this, any book or anything, can i refer, until you start??

  11. Punit says:

    hey i have one confusion can you tell, Instead of this:

    BufferedReader getInfo = new BufferedReader(new FileReader(listOfNames));

    why i can’t do like this directly:

    FileReader getInfo = new FileReader(listOfNames);

    • admin says:

      You use the BufferedReader so that everything is transfered in bulk. You could always call for the buffer to flush the data earlier at any time, but I couldn’t think of any reason why that would be needed. I’m trying to both cover everything while not boring people by going into topics that would almost never be used. It is a juggling act sometimes πŸ™‚

  12. Punit says:

    okay…

  13. Borko says:

    Hi Derek.First a got to say awesome tutorials. Second i have a problem with the printWriter i think i cant write to a file, the source code is bellow. It puts out no errors but the file is blank. Thanks in advance for the help.

    P.S The names of the variables and methods are in Macedonian, sorry if it is an added difficulty !!!

    package seshto;

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;

    public class CitanjePisenje {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub

    Klienti[] klienti = PrevzemiKlienti();

    PrintWriter pisar = fajlMenazder(“D:/Java Fajlovi/Klienti.txt”);

    for(Klienti licnost: klienti)
    {
    ZapisiKlient(licnost, pisar);
    }

    }

    private static class Klienti
    {

    String ime,prezime;
    int godini;

    public Klienti(String Ime,String Prezime,int Godini)
    {
    this.ime = Ime;
    this.prezime = Prezime;
    this.godini = Godini;
    }

    }

    private static Klienti[] PrevzemiKlienti()
    {
    Klienti[] mushteri = new Klienti[5];

    mushteri[0] = new Klienti(“Borko”, “Novacevski”, 25);
    mushteri[1] = new Klienti(“Spire”, “Novacevski”, 25);
    mushteri[2] = new Klienti(“Mile”, “Novacevski”, 25);
    mushteri[3] = new Klienti(“Kire”, “Nadevski”, 21);
    mushteri[4] = new Klienti(“Pece”, “Novevski”, 23);

    return mushteri;
    }

    private static PrintWriter fajlMenazder(String imeNaFajl)
    {

    try {
    File fajl = new File(imeNaFajl);
    PrintWriter pisar = new PrintWriter(new BufferedWriter(new FileWriter(fajl)));
    return pisar;
    } catch (IOException e) {
    // TODO: handle exception
    System.err.println(“Neshto e greshka so fajlMenadzero”);
    System.exit(0);
    }

    return null;
    }

    private static void ZapisiKlient(Klienti mushterija,PrintWriter pisar)
    {

    String notar = mushterija.ime+” “+mushterija.prezime+” “;
    notar += Integer.toString(mushterija.godini);
    pisar.println(notar);
    }
    }

    • Borko says:

      Found it. i didn’t close the print writer so it couldn’t it finish writing!!!

      • admin says:

        Awesome! I’m glad you figured it out. Sorry I couldn’t help quicker. It is amazing to me that people all over the world are watching my videos πŸ™‚

        • Borko says:

          The amazing thing is that i found you and your tutorials they are a great help to me. Cant wait for your J2EE tutorials πŸ˜€

          • admin says:

            Thank you πŸ™‚ I’m glad you found me and found my tutorials useful. I don’t go out of my way to promote myself. I figure if people find me they will. I’ll get to J2EE asap. By the end I have one goal which is to completely cover all of javas core technologies

  14. Hello Derek…

    I am watching each video of your tutorials…
    really they are great!!!
    Thanks so much for your effort..

    I have a doubt…seems your video have a bug

    When you declare this line

    PrintWriter custOutput = createFile(“/Users/derekbanas/Documents/workspace3/Java Code/src/customers.txt”);

    The createFile method in the video always return null….(check the video starting from minute 6.00 and starting from 8.20)
    But here in your code exists the line
    “return infoToWrite;”

    Therefore in your video this line “return infoToWrite;” is missing…

    Later in the video when you work with the reader (Starting from 9.05)… the method createFile not exists in the Java class anymore…

    Again thanks so much for your work!!!

    Kind Regards

    • Derek Banas says:

      Sorry about that. In the past I on occasion would make minor changes here and there and I wouldn’t properly address those changes in the video. I definitely stopped doing that quite a while ago. I apologize if that caused any confusion

  15. Anonymous says:

    Hello, Is there a way through which, we can create our own video module in java? were we can chat through video from 1 system to another?

  16. Anonymous says:

    Hello, is there a code where we can do video chat through java from 1 system to another?

  17. eazl says:

    Hi Derek,

    You are a good teacher. Here is my question. Why define as ‘private’ the class Customer and its variables ‘public’?

    thanks so much,
    eazl

    • Derek Banas says:

      Hi Eazl,

      Thank you πŸ™‚ The answer to the question is because I wanted to focus on PrintWriter, BufferedWriter, FileWriter, etc. in this tutorial.

      You are correct that it is important to encapsulate your code. When I’m making a tutorial though some times I need to make a judgement call on whether encapsulation and the extra methods required to use it will get in the way of what I’m focusing on.

      I trust that people that have no idea what encapsulation is won’t miss it and that those that do know will understand that when I make these videos I focus on topics rather then optimized code.

      I hope that makes sense πŸ™‚
      Derek

  18. Sham says:

    Hello Derek,
    You explained me, why to use static keyword for Monsterboard[][] data memeber within a class, reason is, action is not getting attributed to that data member.

    But I was bit puzzled when you wrote below line:
    public static class Customer { }
    Now i want to understand, why/when to use static keyword for class Customer,
    and also you are placing non-static members within this class.
    public String firstName, lastName;
    public int custAge;

    Am bit confused on this.

  19. Sham says:

    Hello Derek,
    How System.out.println() is able to print any kind of object?
    System.out.println(custInfo);
    How does println() method know the structure & type of data under custInfo?

  20. kuldeep says:

    Hi Derek,

    EVerything is running fine for me.However, once it finishes the execution program throws null Pointer exception. the while loop is entering the last time and it finds that
    String[] indivCustData = custInfo.split(” “); //this string is NULL
    however the bufferedReader is not as it comes in the loop !
    I am unable to figure out that why it is not finding null for the while loop ..

    Thanks

  21. kuldeep says:

    Hello Derek, i have one doubt in this video. Why is that you create methods like createFile as private and yet static, also why do you do similarly for class Customer? I mean can you please tell what are the benefits of doing so and which cases we shall do so ?

    Thanksο»Ώ

    • Derek Banas says:

      I defined Customer as a private static inner class because it doesn’t need access to the members of the outer class. It is private because no other classes should access it. It is a utility class and I don’t want it to be used for any other purpose.

  22. Ben says:

    Hi,
    First thanks a lot again for your awesome tutorials.
    Then, usually in many tools you see there are two options for loading a file:
    one is to load a file from hard disk that is straight forward.
    The other is to load the file from web. Could you explain what I need to be able to do this?
    Thanks in advance

    • Derek Banas says:

      You’re very welcome πŸ™‚ To load a file from the internet do something like this

      URL url = new URL(“http://www.yoursite.com/yourfile.txt”);
      Scanner s = new Scanner(url.openStream());

      • Ben says:

        Thanks a lot Derek
        Now I get an XML file with the method you said
        URL url = new URL(β€œhttp://sth.com/file.xml”)
        Scanner s = new Scanner(url.openStream());
        I have used your tutorial for parsing XML files, but there you parse a file. How can I parse this stream?

  23. Charles-Alexis says:

    After some experiementation(and few research on the web) i understand correctly the IO. But there is something i don’t get : how to add a new line in a file.

    All the String that get into my file end on the same line. For some reasons there is intrinsic “\n” in those lines. I want to be able to see them, to make the file look clear, not just a clump of characters.

    I saw BufferedWriter.newLine() ( Here) could add a new lines, i just get how to do it. I can’t make it work for me. Can you please help me?

    By the way i read some programming blog and you are by far the best in my opinion. Always well detailed and well explained. Plus you got a good rythm and the source are perfectly detailed. Thanks

Leave a Reply

Your email address will not be published.

Google+