.txt file seems to be different when opened on my computer. It seems to be OK on any other mobile device

StackOverflow https://stackoverflow.com/questions/20682355

Question

I've got a strange problem with my newly made .txt file.

My Android Program is writing a string to a .txt file.

Here's my method:

 public void generateNoteOnSD(String sFileName, String sBody){
        try
        {
            File root = new File(Environment.getExternalStorageDirectory(), "Grafy");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, sFileName + ".txt");
            FileWriter writer = new FileWriter(gpxfile);
            writer.append(sBody);
            writer.append("**************\n");
            writer.flush();
            writer.close();
            Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

Here's how i invoke my method:

String s = "0 1 0 0 1 0\n1 0 1 0 1 0\n0 1 0 1 0 0\n0 0 1 0 1 1\n1 1 0 1 0 0\n0 0 0 1 0 0\n";

        generateNoteOnSD("test", s);

The problem is that my .txt file looks like this(when i open it on my mobile):

0 1 0 0 1 0
1 0 1 0 1 0
0 1 0 1 0 0
0 0 1 0 1 1
1 1 0 1 0 0
0 0 0 1 0 0
**********************

But when i open this file on my Computer the '\n' chars are gone... o.o and file looks like this:

0 1 0 0 1 01 0 1 0 1 00 1 0 1 0 00 0 1 0 1 11 1 0 1 0 00 0 0 1 0 0**********************

Where's the problem? :(

Was it helpful?

Solution

Line breaks are composed of "\r\n" (Carriage Return + Line Feed) in Windows operating systems, while in *NIX they are composed of only "\n". This is why it works in your mobile phone, which is likely to be running on the Linux kernel, while on your Windows machine it doesn't.

There is no real harm to saving newlines as "\r\n" instead of just "\n", this will display correctly on both Windows and Linux operating systems.

The Wikipedia article on Newlines provides good information about this matter.

Here is a handy list of text editors, along with their newline support. You can use an editor that supports UNIX newlines without making changes to the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top