我有一个日志类用于写入应用程序内部存储空间中的文件。每当日志文件超过大小限制时。为了清除内容,我将关闭当前的FileOutputStream并使用Write模式创建一个新流并关闭它。有没有更好的方法来实现这一目标:
public final void clearLog() throws IOException {
synchronized (this) {
FileOutputStream fos = null;
try {
// close the current log file stream
mFileOutputStream.close();
// create a stream in write mode
fos = mContext.openFileOutput(
LOG_FILE_NAME, Context.MODE_PRIVATE);
fos.close();
// create a new log file in append mode
createLogFile();
} catch (IOException ex) {
Log.e(THIS_FILE,
"Failed to clear log file:" + ex.getMessage());
} finally {
if (fos != null) {
fos.close();
}
}
}
}
答案 0 :(得分:2)
您也可以不用任何内容覆盖您的文件。
<强>更新强>:
getFilesDir ()似乎有更好的选择看看这个问题How to delete internal storage file in android?
答案 1 :(得分:1)
将空数据写入文件:
String string1 = "";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", false);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write(string1);
fWriter.flush();
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
在此代码中:
fos = new FileOutputStream("/sdcard/filename.txt", false);
FALSE
- 用于撰写新内容。如果TRUE
- 文本附加到现有文件。
答案 2 :(得分:0)
public void writetofile(String text){ // text is a string to be saved
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", false); //false will set the append mode to false
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(text);
outputWriter.close();
readfromfile();
Toast.makeText(getApplicationContext(), "file saved successfully",
Toast.LENGTH_LONG).show();
}catch (Exception e) {
e.printStackTrace();
}
}