-2

我使用以下代码创建了一个 data.txt :

String data = "etc etc etc etc。。" 
                   try {
                   FileOutputStream fOut;

                   fOut = openFileOutput("data.txt", MODE_WORLD_READABLE);

                   OutputStreamWriter fw = new OutputStreamWriter(fOut); 

                   fw.write(data);
                   fw.flush();
                   fw.close();

                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();

但是我怎么知道它被写入了哪里?如何为我的 data.txt 定义路径?

我想使用其他活动来阅读它,所以我还需要知道如何从路径中读取..

4

2 回答 2

0

你可以这样做...

     static final String FILE_LOG = "log.txt";

    String s = "Hello";
            File file;
            FileOutputStream fos = null;

            try
            {
                file = new File(getExternalFilesDir(null), FILE_LOG);
                fos = new FileOutputStream(file);
            }
            catch(FileNotFoundException e)
            {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
                return;
            }

            try
            {
                fos.write(s.getBytes());
                fos.close();
            }
            catch(IOException e)
            {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
                return;
            }

   String path = file.getAbsolutePath().toString();
   Toast.makeText(this, "File is saved to " + path, Toast.LENGTH_SHORT).show();
   Log.e("PATH", path);

希望这会帮助你。

谢谢...

于 2012-10-16T13:11:46.047 回答
-1

我认为这会起作用:

File root = Environment.getExternalStorageDirectory();
String data = "etc etc etc etc。。";
try{
    if (root.canWrite()){
        File txtfile = new File(root, "data.txt");
        FileWriter txtwriter = new FileWriter(txtfile, true);
        BufferedWriter out = new BufferedWriter(txtwriter);
        out.write(data);
        out.close();
    }
}
catch (IOException e){
    e.printStackTrace();
}

}

此代码将在您的外部存储根目录中创建一个 data.txt 文件。不要忘记将此权限添加到您的 AndroidManifest.xml 文件中:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
于 2012-10-16T18:31:51.497 回答