2012-06-07 77 views
0

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

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

回答

2

你也可以覆盖你的文件没有。

UPDATE

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

+0

如何覆盖我以附加模式打开文件?感谢您的建议。 – ssk

+0

嗯,是的,我的意思是在'MODE_PRIVATE'中打开,以覆盖内容。你是对的,我认为你做对了。 –

+0

查看更新。 –

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 - 文本追加到现有文件。

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