0

Hi I am sort of new to java and am trying to extract a string from a .txt file.

 BufferedReader br = new BufferedReader(new FileReader("file.txt"));
    try {
      StringBuilder sb = new StringBuilder();
      String line = br.readLine();
        while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
      }
      String everything = sb.toString();
    } 
    catch(IOException e) 
    {  
    }
    finally {
      br.close();
    }

my issue is that

  1. when I compile this i get an error message --> cannot find symbol symbol : method lineSeparator() location: class java.lang.System. This error message does not occur when i try to compile the line with a different method from the System class.

  2. When I try to comment off this line to see if the rest works smoothly, I get another error message --> unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown. Any explanation for how to fix my issue with not being able to access this method and/or how to get rid of the second error message would be appreciated.

MariuszS
  • 30,646
  • 12
  • 114
  • 155

2 Answers2

4

The System.lineSeparator() method was added in Java 7. There is no javadoc entry for it in Java 6. Make sure you have JDK version 7.

As for the FileNotFoundException, read any of the many related questions/answers.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

Try to seperate the lines like this instead:

sb.append(line + "\n");

For the io.FileNotFoundException,

new FileReader("src/file.txt"));
user3152069
  • 408
  • 3
  • 9
  • That solves my first problem, thanks! Still getting that error message for the second part saying --> unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown for the lines BufferedReader br = new BufferedReader(new FileReader("filename.txt")); and br.close(); – martinmaster43 Jan 11 '14 at 23:20
  • add `throws IOException` to your method :) – – MariuszS Jan 11 '14 at 23:25