views:

492

answers:

1

Hi everyone,

I'm kinda stuck with something which must be appalingly simple. I'm trying to write a few variables to a file, each on it's own line so that I'll be able to use readLine in another method to read the variables back in.

Here's the code:

package com.example.files2;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class files2 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String string1 = "Hey you";
    String string2 = "Is there anybody there";
    String string3 = "Can you hear me";

    setContentView(R.layout.main);

    try{

    File file = new File(Environment.getExternalStorageDirectory(), "file.txt");


    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    writer.write(string1);
    writer.newLine();
    writer.write(string2);
    writer.newLine();
    writer.write(string3);
    writer.newLine();
    writer.flush();
    writer.close();

} catch (IOException e) {
    e.printStackTrace();
}

}}

The file writes OK, but instead of each variable being on it's own line, I get just one line which reads'Hey youIs there anybody thereCan you hear me'.

So I guess .newLine() isn't working but why?

Is there a simple answer to this problem or a better way to achieve it?

Thanks all, comments warmly appreciated.

Joe

+2  A: 

You sure it's not working? Are you using Windows? I imagine Android, being a UNIX based OS is writing \n instead of \r\n like Windows is expecting. What do you see if you type adb shell and then cat /sdcard/file.txt?

synic
Ah! Something else new learned! You guys are lifesavers! Thank you so much!
Joe K 1973