My Question: How do I force an input stream to process line separators as the system standard line separator?
I read a file to a string and the newlines get converted to \n but my System.getProperty("line.separator"); is \r\n. I want this to be portable, so I want my file reader to read the newlines as the system standard newline character (whatever that may be). How can I force it? Here are my methods from the Java Helper Library to read the file in as a string.
/**
* Takes the file and returns it in a string. Uses UTF-8 encoding
*
* @param fileLocation
* @return the file in String form
* @throws IOException when trying to read from the file
*/
public static String fileToString(String fileLocation) throws IOException {
InputStreamReader streamReader = new InputStreamReader(new FileInputStream(fileLocation), "UTF-8");
return readerToString(streamReader);
}
/**
* Returns all the lines in the Reader's stream as a String
*
* @param reader
* @return
* @throws IOException when trying to read from the file
*/
public static String readerToString(Reader reader) throws IOException {
StringWriter stringWriter = new StringWriter();
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) > 0) {
stringWriter.write(buffer, 0, length);
}
reader.close();
stringWriter.close();
return stringWriter.toString();
}
Your
readerToStringmethod doesn’t do anything to line endings. It simply copies character data – that’s all. It’s entirely unclear how you’re diagnosing the problem, but that code really doesn’t change\nto\r\n. It must be\r\nin the file – which you should look at in a hex editor. What created the file in the first place? You should look there for how any line breaks are represented.If you want to read lines, use
BufferedReader.readLine()which will cope with\r,\nor\r\n.Note that Guava has a lot of helpful methods for reading all the data from readers, as well as splitting a reader into lines etc.