Android will not write a new line in a text file

I am trying to write a new line in 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 tried \n, \r\nand I also tried to get the system property for a new line, none of them work.

The data variable contains previously 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();
}
+5
source share
3 answers

I followed a similar program, and it worked for me. However, I noticed strange behavior. He added these new lines to the file, but the cursor remained on the first line. If you want to check, write Stringafter the newlines, you will see what Stringis written just below these newlines .

0
source

, .

: , :

while (readString != null) {
                datax.append(readString);
                readString = buffreader.readLine();
            }

, .

"" - , , , - , : - (

, , :

while (readString != null) {
                datax.append(readString);
                datax.append("\n");
                readString = buffreader.readLine();
            }
+2

I had the same problem and could not write a new line. Instead, I use BufferdWritter to write a new line to a file, and this works for me. Here is an example sniplet code:

OutputStreamWriter out = new OutputStreamWriter(openFileOutput("cache.txt",0));
BufferedWriter bwriter = new BufferedWriter(out);
// write the contents to the file
bwriter.write("Input String"); //Enter the string here
bwriter.newLine();
0
source

All Articles