所以即时尝试将我从套接字接收的数据写入文本文件,然后读取这些数据。
我的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 :(得分: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()