我的问题:如何强制输入流将行分隔符处理为系统标准行分隔符?
我将文件读入字符串,换行符被转换为\n
但我System.getProperty("line.separator");
的是\r\n
. 我希望它是可移植的,所以我希望我的文件阅读器将换行符作为系统标准换行符读取(无论是什么)。我怎么能强迫它?这是我从Java Helper Library 中读取文件作为字符串的方法。
/**
* 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();
}