此代码的目标是在ABCPrint文件夹中保存名为test.txt的文本文件
它当前正在创建文件夹并创建test.txt文件,但是当我打开文件时,其中没有文本。我已经尝试了一切,从它看来它不是一个权限问题。
有没有人看到下面的代码有什么问题会阻止它将字符串写入文件?
try {
File testFolder = new File(Environment.getExternalStorageDirectory(),"ABCPrint");
testFolder.mkdirs();
File file = new File(testFolder, "test.txt");
boolean isnew =file.createNewFile();
FileOutputStream fileOut = openFileOutput(file.getName(), Context.MODE_WORLD_WRITEABLE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);
outputWriter.write("Hello World!");
outputWriter.write("\n");
outputWriter.flush();
outputWriter.close();
fileOut.flush();
fileOut.close();
} catch (Exception e) {
Log.i("Error", "Here", e);
}
答案 0 :(得分:3)
每次调用此行时,都会再次创建文件。还有另一种简单的方法:
File testFolder = new File(
Environment.getExternalStorageDirectory(),
"ABCPrint");
if (!testFolder.exists())
{
try
{
testFolder.createNewFile();
}
catch (IOException e){
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(testFolder, true));
buf.append("Hello World!");
buf.newLine();
buf.close();
}
catch (IOException e){
e.printStackTrace();
}
祝你好运。