0

I am reading a file with one paragraph at a time seperated by a newline.

Line 1
Line 2
Line 3

Line 4
Line 5
Line 6

Here I read Lines 1, 2, 3 and then Lines 4, 5, 6.

while (there are still more paragraphs) {
  String paragraph = new Scanner(new File("testdata.txt")).useDelimiter("\n\n").next();
}

The delimeter "\n\n" is to identify paragraph and not a line. Now, the delimiter can change into "\r\n\r\n" in few systems and "\n\n" in other few. Is there any way to identify it at runtine and use it? I am looking for something like:

String delimiter = getNewLineCharYourself();
String paragraph = new Scanner(new File("testdata.txt")).useDelimiter(delimiter).next();

4 Answers4

6

You are looking for

System.getProperty("line.seperator");
jlordo
  • 37,490
  • 6
  • 58
  • 83
2

Check this out:

String newLine = String.format("%n"); 
//       %n becomes newline     ^^

Or:

System.getProperty("line.separator");

Or, in Java 7:

System.lineSeparator();

From here: How do I get a platform-dependent new line character?

Community
  • 1
  • 1
jsedano
  • 4,088
  • 2
  • 20
  • 31
0

You can just grab the entire file as you have it, and then split the data:

for ( String line : "the entire file".split( System.getProperty("line.separator") )
{
     System.out.println( line );
}

is the universal new line character.

An alternative method:

BufferedReader bufferedReader = new BufferedReader( new FileReader( "absolute file path" ) );

String line;

while ( ( line = bufferedReader.readLine() ) != null)
{
     System.out.println( line );
}
Ganesh Rengarajan
  • 2,006
  • 13
  • 26
0

What jlordo says. Or use a BufferedReader:

File file = new File("myFile.txt");
if (file.exists() && file.canRead()) {
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = null;
        while ((line = br.readLine())!= null) {
            if (!line.trim().isEmpty()) {
                // TODO something with your line
            }
        }
    } 
    catch (Throwable t) {
        // TODO handle this
        t.printStackTrace();
    }
    finally {
        // attempting to close
        if (br != null) {
            try {
                br.close();
            }
            catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
}
Mena
  • 47,782
  • 11
  • 87
  • 106