-1

Ok, I know this is a really rookie question, but I looked around online a lot and am yet unable to find the answer to my question:

How can I read input from a file line by line in java?

Assume a file input that has integers on each line, like:

1
2
3
4
5

Here's the snippet of code I am trying to work with:

public static void main(File fromFile) {

  BufferedReader reader = new BufferedReader(new FileReader(fromFile));

  int x, y;

  //initialize
  x = Integer.parseInt(reader.readLine().trim());
  y = Integer.parseInt(reader.readLine().trim());

}

Presumably, this would read in the first two lines and store them as integers in x and y. So going off the example, x=1, y=2.

It is finding a problem with this, and I don't know why.

AnujSuper9
  • 169
  • 1
  • 12
  • can you post any stack strace? – lweller Jan 19 '11 at 07:32
  • Please elaborate what the problem with the current code is. Do you get an error? Is it just the fact that this presumably only reads 2 lines in stead of 5? Does it not compile or does it not run? – Nanne Jan 19 '11 at 07:33
  • `public static void main(File fromFile)` is it !!!! – jmj Jan 19 '11 at 07:35
  • "It is finding a problem with this" is very vague. In this case people have spotted the problem, but in future try to be more specific. If you're getting an error at execution time, post the exception. If you're getting a compile-time error, post that. If you're getting unexpected results, post the expected results (with reasons) and the actual results. See http://tinyurl.com/so-hints for more advice about writing questions well. – Jon Skeet Jan 19 '11 at 07:38

3 Answers3

2

please check your main method(). It should be like these

public static void main(String... args) {
}

or

public static void main(String[] args) {
}

then read like that :

 BufferedReader reader = new BufferedReader(new FileReader(fromFile));

 String line;
 while( (line = reader.readLine()) != null){
        int i = Integer.parseInt(line);
 }
  • How do I initialize the BufferedReader if I can't pass in an input file? As in, where does fromFile go/come from? – AnujSuper9 Jan 19 '11 at 08:31
  • I didn't write it because you did it right. Anyway, I just copy your code (init bufferedreader) –  Jan 19 '11 at 08:34
2
 public static void main(String[] args) {
        FileInputStream fstream;
        DataInputStream in = null;
        try {
            // Open the file that is the first 
            // command line parameter
            fstream = new FileInputStream("textfile.txt");
            // Get the object of DataInputStream
            in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            int x = Integer.parseInt(br.readLine());
            int y = Integer.parseInt(br.readLine());

            //Close the input stream

        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        } finally {
            try {
                in.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
jmj
  • 237,923
  • 42
  • 401
  • 438
0

We usually use a while loop, the readLine method tells whether the end of file is reached or not:

 List<String> lines = new ArrayList<String>();
 while ((String line = reader.readLine()) != null)
   lines.add(line);

Now we have a collection (a list) that holds all lines from the file as separate strings.


To read the content as Integers, just define a collection of integers and parse while reading:

 List<Integer> lines = new ArrayList<Integer>();
 while ((String line = reader.readLine()) != null) {
   try {
     lines.add(Integer.parseInt(line.trim()));
   } catch (NumberFormatException eaten) {
     // this happens if the content is not parseable (empty line, text, ..)
     // we simply ignore those lines
   }
 }
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268