【问题标题】:Read file android读取文件安卓
【发布时间】:2012-10-16 12:57:30
【问题描述】:

我使用此代码创建了一个 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 定义路径?

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

【问题讨论】:

  • 这是标准的 Java 文件 IO。 Google 可以为您指出一千个教程
  • 试了一天,还是不行!!
  • 您应该使用Environment.getDataDirectory() 并在那里创建一个文件。

标签: android filepath android-file


【解决方案1】:

你可以这样做......

     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);

希望这会对你有所帮助。

谢谢...

【讨论】:

    【解决方案2】:

    我认为这会奏效:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多