0

我有一个日志记录类,用于写入应用程序内部存储空间中的文件。每当日志文件超过大小限制时。为了清除内容,我将关闭当前的 FileOutputStream 并使用写入模式创建一个新流并将其关闭。有没有更好的方法来实现这一点:

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();
                }
            }
        }
    }
4

3 回答 3

2

您也可以一无所有地覆盖您的文件。

更新

getFilesDir ()似乎有更好的选择看看这个问题How to delete internal storage file in android?

于 2012-06-07T22:08:25.400 回答
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- 用于编写新内容。If TRUE- 文本附加到现有文件。

于 2014-03-13T07:54:11.133 回答
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();  
    }  
}
于 2015-03-03T17:51:54.163 回答