Android does not write new lines in text files… here is a solution to the problem.
Android does not write new lines in text files
I’m trying to write a new line to a text file in android.
Here is my code:
FileOutputStream fOut;
try {
String newline = "\r\n";
fOut = openFileOutput("cache.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.write(newline);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I’ve \n
tried , and I’ve also tried getting the system properties for line breaks,\r\n
but none of them work.
The data variable contains previous data from the same file.
String data = "";
try {
FileInputStream in = openFileInput("cache.txt");
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "ISO8859-1");
BufferedReader inRd = new BufferedReader(isr,8 * 1024);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
}
in.close();
data = inLine.toString();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Best Solution
I had the same problem, tried all the tricks in the book.
My question: line breaks are written, but when reading they are removed:
while (readString != null) {
datax.append(readString);
readString = buffreader.readLine();
}
Files are read and concatenated line by line, so the newline characters disappear.
I didn’t look at the original file in Notepad or something because I don’t know where to look on my phone, my log screen uses the code to remove line breaks 🙁
So the easiest way is to put it back while reading:
while (readString != null) {
datax.append(readString);
datax.append("\n");
readString = buffreader.readLine();
}