写入内部存储 - 文件为空

时间:2011-08-15 14:49:35

标签: android

我正在尝试以多种方式将文本文件写入内部存储。我不知道为什么结果文本文件是空的。

package com.testandroid;

public class TestAndroidActivity extends Activity {
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        writeToInternalStorage(this);
    }

    private void writeToInternalStorage(final Context context) {
        try {
            // Way1
            final PrintWriter writer = new PrintWriter(new File("/data/data/com.testandroid/test.txt"));
            writer.println("Something");

            // Way2
            final PrintWriter writer2 = new PrintWriter(new FileOutputStream("/data/data/com.testandroid/test2.txt"));
            writer2.write("Something more");

            // Way3
            final FileOutputStream fos = openFileOutput("test3.txt", Context.MODE_PRIVATE);
            final PrintWriter writer3 = new PrintWriter(fos);
            writer3.write("Something of something");
            try {
                fos.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }

            // Way4
            try {
                final BufferedWriter writer4 = new BufferedWriter(new FileWriter(new File("/data/data/com.testandroid/test4.txt")));
                writer4.write("Something please");
            } catch (final IOException e) {
                e.printStackTrace();
            }

        } catch (final FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个

  FileWriter outFile = new FileWriter("/data/data/com.testandroid/test.txt");
    PrintWriter out = new PrintWriter(outFile);
    // Printwriter out = new PrintWriter(new FileWriter("/data/data/com.testandroid/test.txt"));
    out.println("This is line 1");
out.close();