Schwarz Schwarz - 4 months ago 19
Java Question

String.split won't split with \n when reading a string from a file

This is on Windows. It worked when I had the \n in a string I created in the class but it doesn't when reading the same string from a file.

String[] string = str.split(" \\n| |\\n|\n");


Example of string in file:


This is a test.\nColor: [blue yellow black green red]\nDates:


If the code I use to read from the file is of any relavalence:

public static String getStringArray(String filename) {
try {
return IOUtils.toString(new FileInputStream(filename), Charset.defaultCharset());
} catch(IOException ex) {
Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}


This is using org.apache.commons.io.IOUtils.

Answer

Firstly, a method called getStringArray should return String[], not String.

Also, the regex "(\\n|\r?\n)" does what you expect (according to my understanding).

It breaks the lines either by literal "\n" or by line-breaks.

public static String[] getStringArray(String filename)
{
    try
    {
        String content = IOUtils.toString(new FileInputStream(filename), Charset.defaultCharset());
        String[] lines = content.split("(\\\\n|\\r?\\n)");
        return lines;
    } catch (IOException ex)
    {
        Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

Or, in a reduced way:

public static String[] getStringArray(String filename)
{
    try { return IOUtils.toString(new FileInputStream(filename), Charset.defaultCharset()).split("(\\\\n|\\r?\\n)"); }
    catch (IOException ex) { Logger.getLogger(File.class.getName()).log(Level.SEVERE, null, ex); }
    return null;
}

If you iterate over the returned array (using your sample string), you will get:

This is a test.

Color: [blue yellow black green red]

Dates:

Comments