【问题标题】:Android Studio read/write from .txt file, save path?Android Studio 从 .txt 文件读/写,保存路径?
【发布时间】:2016-05-23 15:13:34
【问题描述】:

所以我试图将从套接字接收的数据写入文本文件,然后读取这些数据。

我的 MainActivity 中有这 2 种方法(只是测试看看读写文件的工作原理):

public void WriteBtn() {


    // add-write text into file
    try {
        FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
        outputWriter.write("Test");
        outputWriter.close();

        //display file saved message
        Toast.makeText(getBaseContext(), "File saved successfully!",
                Toast.LENGTH_SHORT).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
public void ReadBtn() {
    //reading text from file
    try {
        FileInputStream fileIn=openFileInput("mytextfile.txt");
        InputStreamReader InputRead= new InputStreamReader(fileIn);

        char[] inputBuffer= new char[256];
        String s="";
        int charRead;

        while ((charRead=InputRead.read(inputBuffer))>0) {
            // char to string conversion
            String readstring=String.copyValueOf(inputBuffer,0,charRead);
            s +=readstring;
        }
        InputRead.close();
        Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();

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

我用按钮调用它们,但我想知道,它把我的“mytextfile.txt”保存在哪里???

【问题讨论】:

标签: android


【解决方案1】:

查看 Context.getExternalFilesDir() 并将其传递给 Environment.DIRECTORY_DOCUMENTS。这应该为您提供文本文件的默认输出路径。 https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

编辑 我刚刚测试了这个。看起来 Context.openFileOutput() 将所有内容(无论文件类型如何)都转储到 Conext.getFilesDir() https://developer.android.com/reference/android/content/Context.html#getFilesDir()

【讨论】:

  • 我设法使用 getFilesDir() /data/user/0/sevrain.test/files 检索了路径,在资源管理器中是否可以访问它?
  • @Sech,应用程序的文件目录是应用程序内部和私有的,因此文件浏览器将无法浏览除非手机已root(或您正在使用模拟器)。您可以在您的应用程序中嵌入您自己的文件浏览器(尝试 getFilesDir().listFiles() 获取内部文件列表)。或者,如果您不想保护文件,您可以只写出到共享内存 - 不要使用 getFilesDir() 而只是使用公共存储的路径,如 new FileOutputStream("/sdcard/mytestfile.txt" );
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多