1

I have a method in java which returns the updated lines of a flat file as a "String". I am receiving the String as a bunch of lines, what i want to do is to separate the String line by line. How can i do that in java?????

tpsharish
  • 23
  • 1
  • 1
  • 5

3 Answers3

3
String lines[] = fileString.split("\\r?\\n"); //should handle unix or win newlines
MattMcKnight
  • 8,185
  • 28
  • 35
3

I will suggest make use of system property line.separator for this splitting to make your code work on any platform eg: *nix, Windows, Mac etc. Consider code like this:

String str = "line1\nline2\nline3";
String eol = System.getProperty("line.separator");
System.out.printf("After Split - %s%n", Arrays.toString(str.split(eol)));
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

I am not sure about with single string separator .

but i roughly write a method that may be relevant to you .

public void splitter  (DocumentEvent e) {
    String split[], docStr = null;
    Document textAreaDoc = (Document)e.getDocument();

    try {
        docStr = textAreaDoc.getText(textAreaDoc.getStartPosition().getOffset(), textAreaDoc.getEndPosition().getOffset());
    } catch (BadLocationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    split = docStr.split("\\n");
}
dharmendra
  • 7,835
  • 5
  • 38
  • 71