2016-05-23 1144 views
0

所以即时尝试写入我从套接字到文本文件,然后读取这些数据的数据。Android Studio从.txt文件读取/写入,保存路径?

我有这2种方法在我的MainActivity(只是测试,看看如何读取和/写入到文件中的作品):

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”?

+0

我很确定它是依赖于上下文,保存到它的当前设置文件目录。 http://stackoverflow.com/questions/4926027/what-file-system-path-is-used-by-androids-context-openfileoutput – zgc7009

回答

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

+0

我设法检索路径使用getFilesDir()/数据/用户/ 0/sevrain .test/files 有没有在浏览器中访问它? – Sech

+0

@Sech,应用程序的文件目录是应用程序内部的,并且是私有的,因此文件浏览器将无法浏览_unless_手机已根植(或者您正在使用模拟器)。你可以在你的应用中嵌入你自己的文件浏览器(尝试getFilesDir()。listFiles()来获取内部文件列表)。另外,如果你不想保护文件,你可以写出共享内存 - 不要使用getFilesDir(),而只是使用公共存储路径,比如新的FileOutputStream(“/ sdcard/mytestfile.txt” ); – tpankake