how to detect line breaks in java

34,982

If you have the data already in a String:

String[] lines = string.split("\r\n|\n|\r");
for (String line : lines) {
    System.out.println(line);
}

Or read the lines directly from a file:

BufferedReader br = new BufferedReader(new FileReader("myfilename"));
String line = null;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

Java 7+ has a convenience method to read lines directly from the filesystem:

Path path = FileSystems.getDefault().getPath("myfilename");
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for (String line : lines) {
    System.out.println(line);
}

Java does not do automatic charset detection, so you are responsible for setting the charset correctly when reading a text file; otherwise characters may not be read correctly. Don't forget to be tidy: .close() your file handles.

Share:
34,982
kamil
Author by

kamil

Updated on July 09, 2022

Comments

  • kamil
    kamil almost 2 years

    yes i have read a few of the other posts on line breaks but they are not helping me.

    my Java program is supposed to read a .PHP file and split the source code into a line by line format. the problem is that i cant seem to really distinguish one line break from another.

    i tried to use /n didnt work.... i tried to use /r/n didnt work.....

    here is an example

    step_B = step_A.replaceAll("\n", "XXX");
    

    i tried to replace the line breaks with the word XXX but it didnt work.

    here is a sample of the php i wanted to split, i managed to separate the lines using ; as delimiter but i got to refine it a bit more now.

    $ALL_AUTH = mysql_fetch_row($author_lookup);
        //preparing to display the output in the table
        echo "<tr>";
    

    i wanted it to output something like this

    INFO:  $ALL_AUTH = mysql_fetch_row($author_lookup)
    
    INFO:  //preparing to display the output in the table 
    
    INFO:  echo "<tr>"
    

    but instead i get this

    INFO:  $ALL_AUTH = mysql_fetch_row($author_lookup)
    
    INFO:  //preparing to display the output in the table  echo "<tr>"
    

    the app cannot seem to detect that there is a newline after the comment ends at the word "table". is there a way to do this ? preferably without hardcoding the word table or anything like that.

    Ohhhh i found the mistake, i used a transform via some regex on the block of code at an earlier stage and that messed up the newlines.... the code block became one massive line of text ! hence no line breaks thanks for your time guys !

  • Neet
    Neet over 11 years
    This or directly use a BufferedReader to read the text file line by line.