Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Program that reads data from a text file...need help

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Program that reads data from a text file...need help

    I have to write a program that reads data from a txt file. Then, i have to put the data (a string and some integers which need to be put into an arraylist) into an object. But I don't know where to start. Any ideas?


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Program that reads data from a text file...need help

    Break the project up into several small steps.
    First: Write a program to read lines from a file and print them out.

    When that works, add code to convert the data in the lines to the correct format for storing in a class.

    When that works, define a class that will hold the data with a constructor to take the data and store it internally.

    When that works, define an ArrayList and add the class object to it.

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Program that reads data from a text file...need help

    Several ways of doing this:
    The simplest way of doing it is with Scanner ()

    If you are wanting to read larger files, I would recommend BufferedReader().

    So, lets say we have a very basic 5 line text document named "Test.txt" that looks like this:
    Start of File
    5 10 90 20
    78 29 99 7
    64 34 87 21
    End of File
    If we wanted to read each line and get each value, here is how we would do it with each method:
    Scanner:
    //Import Scanner and File
    import java.util.Scanner;
    import java.io.File;
     
    public class ReadingFile
    {
    	//Create Main
        public static void main(String[] args)
        {
        	/* We want to create a TRY/CATCH statement so we can handle any Exceptions we may
        	 * get while attempting to read the file. The TRY statement starts here and ends
        	 * at the end of our main with our CATCH statement.
        	 */
        	try{
     
        	/* Create our Scanner Object. The easiest way of doing this is by sending Scanner
        	 * a File. So, we need to create a new File, whose parameter is the path to the
        	 * file we are wanting to read in. Since the file is located in the same directory
        	 * as our program, we can just provide the name (and extension) instead of the
        	 * entire path.
        	 */
        	Scanner input = new Scanner(new File("Test.txt"));
     
        	/* Get the First Line of Text from our Document. Since we know the first line is
        	 * just a String, the nextLine() method is our preferred method.
        	 */
        	String line = input.nextLine();
        	//Now we display this line to the user
        	System.out.println(line);
     
        	/* Now we want to get each int in each line. So, we want to use a loop to go through
        	 * the document. Based on what we know about the document, we can continue to go until
        	 * we no longer have any ints left. We can do this by using the hasNextInt() method.
        	 */
        	while(input.hasNextInt())
        	{
        		/* Now, Scanner allows us to parse the line while we read it in. So, instead of
        		 * reading in the line as a String, we can actually read in each int one at a time.
        		 * We do this with the nextInt() method.
        		 */
        		int value = input.nextInt();
        		//Now we want to print this out to the user
        		System.out.println(value);
     
        		//This loop will continue until it reaches the line that reads: "End of File"
        	}
        	/* Now that we have read in all the ints and printed them out to the user, we want to
        	 * read in the last line and print that out to the user. For whatever reason, I seem
        	 * to be having trouble reading in the line. However, if we read in each String of
        	 * the line, there doesn't seem to be an issue. Someone will probably know how to fix
        	 * this, I don't use Scanner much.
        	 */
        	line = input.next()+" "+input.next()+" "+input.next();
        	//Now we print this line to the user
        	System.out.println(line);
     
        	//Now that we are done, we want to close the text document we read from.
        	input.close();
     
        	/* Lastly, we want to provide the catch statement that will print out any errors that
        	 * occur so we can deal with them.
        	 */
        	}catch(Exception ex){System.out.println(ex);}
        }
    }

    BufferedReader:
    //Import Buffered, FileReader and StringTokenizer
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.StringTokenizer;
     
    public class ReadingFile2
    {
    	//Create Main
        public static void main(String[] args)
        {
        	/* We want to create a TRY/CATCH statement so we can handle any Exceptions we may
        	 * get while attempting to read the file. The TRY statement starts here and ends
        	 * at the end of our main with our CATCH statement.
        	 */
        	try{
     
        	/* Create our BufferedReader Object. Now, BufferedReader requires we send it a Reader.
        	 * So, we can create an arbitrary FileReader Object, whose parameter is the path to the
        	 * file we are wanting to read in. Since the file is located in the same directory
        	 * as our program, we can just provide the name (and extension) instead of the
        	 * entire path.
        	 */
        	BufferedReader input = new BufferedReader(new FileReader("Test.txt"));
     
        	/* Get the First Line of Text from our Document. The readLine() method is our preferred
        	 * method for all Line Reading when using BufferedReader.
        	 */
        	String line = input.readLine();
        	//Now we display this line to the user
        	System.out.println(line);
     
        	/* Before entering the loop that reads the rest of the file, we want to advance the line
        	 * by using the readLine() method again. Doing this will make sense later.
        	 */
        	line = input.readLine();
     
        	/* Now we want to get each int in each line. So, we want to use a loop to go through
        	 * the document. Based on what we know about the document, we can continue to go until
        	 * we no run into the line that reads: "End of File". When using BufferedReader, we have
        	 * to read in each line, so we can do this by comparing the value of our line variable.
        	 * BEWARE OF INFINITE LOOPS! To hopefully prevent infitite loops AND to prevent null
        	 * pointers, we also take into account of line being null (no more lines in file).
        	 */
        	while(!line.equals("End of File") && line!=null)
        	{
        		/* Now, BufferedReader doesn't allow us to do things so easily as Scanner. We have
        		 * to use something called a StringTokenizer to parse through each line. When we
        		 * create a StringTokenizer, we want to send it the line we are reading in.
        		 */
        		StringTokenizer tokenizer = new StringTokenizer(line);
        		/* Now we want to get all the ints out of this line. So, we are going to assume we
        		 * don't know how many ints there are. Which means we need to loop through the
        		 * tokenizer. To do this, we use the hasMoreTokens() method in our WHILE Loop.
        		 */
        		while(tokenizer.hasMoreTokens())
        		{
        			/* Now we get each token using the nextToken() method. Since this method returns
        			 * a String, we need to parse it into an int using the Integer.parseInt(String)
        			 * method.
        			 */
        			int value = Integer.parseInt(tokenizer.nextToken());
        			//Now we want to print this out to the user
        			System.out.println(value);
        		}
     
        		/* Lastly, remember we need to advance the line. Just make another call to the readLine()
        		 * method and that does the trick.
        		 */
    			line = input.readLine();
        		//This loop will continue until it reaches the line that reads: "End of File"
        	}
        	/* Now that we have read in all the ints and printed them out to the user, we want to
        	 * read in the last line and print that out to the user. The good news is that we already
        	 * have the last line read in, thanks to the readLine() call in the loop. So, we just need
        	 * to print it out.
        	 */
        	System.out.println(line);
     
        	//Now that we are done, we want to close the text document we read from.
        	input.close();
     
        	/* Lastly, we want to provide the catch statement that will print out any errors that
        	 * occur so we can deal with them.
        	 */
        	}catch(Exception ex){System.out.println(ex);}
        }
     
     
    }

    Both of these programs will give you the exact same output. It is just two different ways of doing it.

    That should answer all your questions regarding how to read IO. This is an important topic, so I want to make sure you understand it all. If you have any questions, just ask them and I'll answer to the best of my ability.
    Last edited by aussiemcgr; October 1st, 2010 at 05:18 PM.

  4. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Starstreak (April 1st, 2013)

  5. #4
    Junior Member
    Join Date
    Oct 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Program that reads data from a text file...need help

    Quote Originally Posted by Norm View Post
    When that works, add code to convert the data in the lines to the correct format for storing in a class.
    how would you do this? for every line of my text file, the format is: <string> <string> <string> <float>

  6. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Program that reads data from a text file...need help

    for every line of my text file, the format is: <string> <string> <string> <float>
    Use the String split method to break the String into 4 parts. Then use the Float class to parse the last part to a float

Similar Threads

  1. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM
  2. Read data from text file
    By yroll in forum Algorithms & Recursion
    Replies: 4
    Last Post: December 31st, 2009, 01:40 AM
  3. write text to a file help
    By wolfgar in forum File I/O & Other I/O Streams
    Replies: 8
    Last Post: November 24th, 2009, 08:36 AM
  4. A program that reads in secounds, and prints out hours minutes
    By CYKO in forum Java Theory & Questions
    Replies: 1
    Last Post: September 13th, 2009, 10:42 PM
  5. Java program to reduce spaces between the words in a text file
    By tyolu in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: May 13th, 2009, 07:17 AM