schwarz
schwarz

Reputation: 521

How to parse end of line string in Java

I would like to read a text file which has some strings such as:

abc  
def

ghi  
jkl

mno  
pqr

I am using a while loop to read only a pair and store them in an arraylist. I would like to stop as soon I encounter an empty line (\n) e.g. after def. But my code wont work ... what am I doing wrong?

while(!"\n".equals(sCurrentLine)) {
     -- do stuff --
}

Upvotes: 1

Views: 2194

Answers (5)

SSaikia_JtheRocker
SSaikia_JtheRocker

Reputation: 5063

You can do something like this

Assumption 1, you are to add pairs skipping empty lines.

    String line = null;
        while ((line = br.readLine()) != null) {
          //when we encounter a empty line we continue
          //the loop without doing anything
          if (line.trim().isEmpty()) {
               continue;
          }
          //add to list
        }

Assumption 2, you want to exit at first empty line

 String line = null;
   while ((line = br.readLine()) != null) {
      //when we encounter a empty line we exit the loop
      if (line.trim().isEmpty()) {
          //break the loop
          break;
      }
      //add to list
    }

Hope this helps.

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

 while(!"".equals(sCurrentLine)) {
 -- do stuff --
 }

This will help you

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class AddToArrayList {
public static void main(String[] args) throws IOException {
    Scanner sc=new Scanner(new File("D:\\Text.txt"));
    ArrayList<String> str=new ArrayList<>();
    String s=null;
    while (sc.hasNext()){
        s=sc.nextLine();
        if(s.equals("")){
             continue;
        }
        str.add(s);
    }
}
}

Upvotes: 2

RiaD
RiaD

Reputation: 47619

If you are reading line by line then empty line is empty line (""), not "\n" which is string of length 1

You may also need check that there's no more lines in this case BufferedReader.readLine() returns null

Upvotes: 8

Dariusz
Dariusz

Reputation: 22241

You are making one big mistake: you're assuming that the newline character is \n, which is not always true. Depending on the operating system it can be either CR, LF or CRLF.

You can keep checking it your way, but you'd have to check it against all these three possibilities.

You can also use String.trim() and then compare the string "".equals(var.trim())

Upvotes: 2

Korashen
Korashen

Reputation: 2191

You should use System.getProperty("line.separator") instead of using a system dependent String.

Upvotes: 0

Related Questions