Java 在Android上清除内部存储中的文件内容
我有一个日志类,用于写入应用程序内部存储空间中的文件。每当日志文件超过大小限制时。为了清除内容,我关闭当前的FileOutputStream,创建一个具有写入模式的新流并关闭它。有没有更好的方法来实现这一点:Java 在Android上清除内部存储中的文件内容,java,android,logging,Java,Android,Logging,我有一个日志类,用于写入应用程序内部存储空间中的文件。每当日志文件超过大小限制时。为了清除内容,我关闭当前的FileOutputStream,创建一个具有写入模式的新流并关闭它。有没有更好的方法来实现这一点: public final void clearLog() throws IOException { synchronized (this) { FileOutputStream fos = null; try {
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();
}
}
}
}
您也可以不使用任何内容覆盖您的文件 更新:
看一下这个问题,似乎有一个更好的选择您也可以不使用任何内容覆盖您的文件 更新:
看看这个问题,似乎有更好的选择将空数据写入文件:
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
-文本附加到现有文件。将空数据写入文件:
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();
}
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();
}
}
在此代码中:
fos = new FileOutputStream("/sdcard/filename.txt", false);
FALSE
-用于编写新内容。如果TRUE
-文本附加到现有文件。在附加模式下打开文件时,如何覆盖?谢谢你的建议。嗯,是的,我的意思是在模式\u PRIVATE
下打开,所以你可以覆盖内容。你是对的,我认为你做得对。当我以附加模式打开文件时,如何覆盖?谢谢你的建议。嗯,是的,我的意思是在模式\u PRIVATE
下打开,所以你可以覆盖内容。你是对的,我认为你做得对。
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();
}
}