Reputation: 29021
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();
}
Upvotes: 3
Views: 5235
Reputation: 22441
You can use a BufferedReader to read the file line by line and convert the line separators, e.g.:
public static String readerToString(Reader reader) throws IOException {
BufferedReader bufReader = new BufferedReader(reader);
StringBuffer stringBuf = new StringBuffer();
String separator = System.getProperty("line.separator");
String line = null;
while ((line = bufReader.readLine()) != null) {
stringBuf.append(line).append(separator);
}
bufReader.close();
return stringBuf.toString();
}
Upvotes: 1
Reputation: 1500185
Your readerToString
method 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 \n
to \r\n
. It must be \r\n
in 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
, \n
or \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.
Upvotes: 2
Reputation: 10900
With the Scanner#useDelimiter method you can specify what delimiter to use when reading from a File
or InputStream
or whatever.
Upvotes: 1
Reputation: 236004
It's advisable to use BufferedReader
for reading a file line-by-line in a portable way, and then you can use each of the lines read for writing to the required output using the line separator of your choice
Upvotes: 2