2

I have been researching how to do this and becoming a bit confused, I have tried so far with Scanner but that does not seem to preserve line breaks and I can't figure out how to make it determine if a line is a line break. I would appreciate if anyone has any advice. I have been using the Scanner class as below but am not sure how to even check if the line is a new line. Thanks

    for (String fileName : f.list()) {

            fileCount++;

            Scanner sc = new Scanner(new File(f, fileName));
            int count = 0;
            String outputFileText = "";

            //System.out.println(fileCount);

            String text="";
            while (sc.hasNext()) {

                String line = sc.nextLine();
            }
}
Rick
  • 16,612
  • 34
  • 110
  • 163
  • 1
    What exactly do you mean by check if the line is a new line? Scanner.nextLine() already breaks up the file into lines for you so all you have to do is scan each invdividual line you get to find values, etc. – donnyton Jun 18 '11 at 04:16
  • If you are using a BufferedWriter, you could also use the .newline method: http://stackoverflow.com/questions/9199216/strings-written-to-file-do-not-preserve-line-breaks – Christian Vielma Feb 09 '16 at 11:40

3 Answers3

3

If you're just trying to read the file, I would suggesting using LineNumberReader instead.

LineNumberReader lnr = new LineNumberReader(new FileReader(f));
String line = "";
while(line != null){
    line = lnr.readLine();
    if(line==null){break;}
    /* do stuff */
}
Darien
  • 3,482
  • 19
  • 35
  • I need to read it line by line and then I am doing some things with the line to check for values (using regex).. thanks I will take a look at `LineNumberReader` – Rick Jun 18 '11 at 01:24
  • As Chuck notes, the superclass `BufferedReader` provides similar functionality. (I just like knowing what line I'm on if I have to craft an error message.) – Darien Jun 18 '11 at 01:26
  • so if it picks up a newline character (for example `\n` ) I could just pass that through to the output string I am creating? – Rick Jun 18 '11 at 01:28
  • The return value of `readLine()` shouldn't have any any newlines in it. (That is, `\r\n`, `\n`, or `\r`.) If `readline() == ""` then you know it saw a line with *only* a newline at the end and no other content. If you're trying to test for lines that contain `\r\n` (from windows) versus `\n` (unix style) then this won't help you because it treats them all the same. – Darien Jun 20 '11 at 17:50
1

Java's Scanner class already splits it into lines for you, even if the line is an empty String. You just have to scan through the lines again to get your values:

Scanner lineScanner;
while(sc.hasNext())
{
    String nextInputLine = sc.nextLine();

    lineScanner = new Scanner(nextInputLine);

    while(lineScanner.hasNext())
    {
        //read the values
    }
}
donnyton
  • 5,874
  • 9
  • 42
  • 60
0

You probably want to use BufferedReader#readLine.