我使用以下代码创建了一个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定义路径?
我想用其他活动来阅读它,所以我需要知道如何从路径中读取..
答案 0 :(得分: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);
希望这会对你有所帮助。
...谢谢
答案 1 :(得分:-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>