开发者

Simple Android File Output Problem

开发者 https://www.devze.com 2022-12-26 07:56 出处:网络
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

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开发者_C百科.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


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?


If this is - in effect - simply a manifestation of the age-old UNIX/DOS linefeed character disparity (that is the file is being written correctly on the Linux based Android device but is not rendered correctly [say in notepad] on a Windows PC) then one answer is to view the file on the PC using Vim (see http://www.vim.org/download.php) or another application that can automagically determine the linefeed character from the file content (and save to a native Windows/DOS format if needed).

Another alternative is to view the file content directly on the Android device, using a text editor such as "Text Edit" available free from the market.

Hope this helps - apologies if I am stating the obvious.

0

精彩评论

暂无评论...
验证码 换一张
取 消