基本上我有两个问题。我使用下面的代码来读写z文本文件。
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();这会在每次我想要OPEN_OR_CREATE的时候创建一个新文件(如果文件已经存在,就不要创建一个新文件)
我的第二个问题是如何更改路径"/ sdcard /mysdfile.txt“我希望此文件存储在我的sdcard -> subFolder1 -> SubFolder2中
技术
发布于 2012-11-21 19:01:54
不要使用硬编码的/sdcard或/mnt/sdcard,否则您的应用程序将失败,因为设备会因该存储的位置或挂载点而异。要获得正确的位置,请使用
Environment.getExternalStorageDirectory();参见docs here。
要将内容附加到现有文件,请使用new FileOutputStream(myFile, true);而不只是new FileOutputStream(myFile); -请参阅docs on that constructor here。
至于
如何更改路径"/sdcard/mysdfile.txt“
除了如上所述的去掉/sdcard之外,只需在路径中添加子文件夹:MyFolder1/MyFolder2/mysdfile.txt。注意:这些文件夹必须存在,否则路径将无效。您始终可以通过调用myFile.mkdirs()来创建它。
发布于 2012-11-21 19:00:15
替换
FileOutputStream fOut = new FileOutputStream(myFile);使用
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.除此之外,我有一个建议给你。
永远不要在代码中硬编码/sdcard,而要考虑编写代码。
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");发布于 2012-11-21 19:01:21
尝试将我的解决方案写入到文本文件末尾
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
https://stackoverflow.com/questions/13491668
复制相似问题