Results 1 to 2 of 2
  1. #1
    Rookie is offline Member
    Join Date
    Jan 2013
    Posts
    2
    Rep Power
    0

    Default Reading a multiple line file with StringTokenizer?

    I have a file of integers:

    3 5
    6

    I want to read the file and put 3, 5, and 6 in separate integers. This is my code so far:

    Java Code:
    import java.io.*;
    import java.util.*;
    
    public class milk2
    {
    	public static void main(String[] args) throws IOException
    	{
    		BufferedReader f = new BufferedReader(new FileReader("milk2.in"));
    		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("milk2.out")));
    		StringTokenizer st = new StringTokenizer(f.readLine());
    		
    		int i1 = Integer.parseInt(st.nextToken());
    		f.readLine(); // I put this in to skip the space in between the first two integers
    		int i2 = Integer.parseInt(st.nextToken());
                    int i3 = Integer.parseInt(st.nextToken());
    		out.println(i1);
    		out.println(i2);
                    out.println(i3);
    		out.close();
    		System.exit(0);
    	}
    }
    Eclipse outputs these warnings:

    Exception in thread "main" java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(Unknown Source)
    at milk2.main(milk2.java:21)

    I know the problem is with reading the second line because if I get rid of int i3, the first two integers are read and stored to i1 and i2 like they should be. But I can't read the next line. So how do I skip to the next line and continue reading?

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,945
    Rep Power
    19

    Default Re: Reading a multiple line file with StringTokenizer?

    StringTokenizer is a legacy class that should no longer be used.
    You should be using String.split() instead.
    That will give you an array of Strings that you can then work with.

    What's happening with yours is that you are trying to read in 3 tokens when the first line only has 2.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. reading particular line from textfile file
    By karrydhawan in forum New To Java
    Replies: 3
    Last Post: 01-05-2012, 12:22 PM
  2. Reading Next Line of File
    By smitsky in forum New To Java
    Replies: 5
    Last Post: 12-04-2011, 05:35 PM
  3. Java- Writing a file and reading a file line by line
    By Nazneen Ali in forum New To Java
    Replies: 7
    Last Post: 07-20-2011, 07:56 AM
  4. Reading a specific line from a file
    By efebatistaarda in forum New To Java
    Replies: 6
    Last Post: 02-22-2011, 02:57 PM
  5. Reading in data from file line by line
    By bluekswing in forum New To Java
    Replies: 1
    Last Post: 10-02-2007, 12:19 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •