2010-04-12 39 views

回答

13

如何:

new RandomAccessFile(fileName).setLength(0); 
1

打開文件進行寫入並保存。它刪除文件的內容。

+8

你的意思是,「對寫開放的文件,_close_它」長? – 2010-04-12 13:05:31

1

你可以通過打開文件for writing and then truncating its content做到這一點,下面的例子使用NIO:

import static java.nio.file.StandardOpenOption.*; 

Path file = ...; 

OutputStream out = null; 
try { 
    out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING)); 
} catch (IOException x) { 
    System.err.println(x); 
} finally { 
    if (out != null) { 
     out.flush(); 
     out.close(); 
    } 
} 

Another way:截斷剛剛過去的20個字節的文件:

import java.io.RandomAccessFile; 


RandomAccessFile file = null; 
try { 
    file = new RandomAccessFile ("filename.ext","rw"); 
    // truncate 20 last bytes of filename.ext 
    file.setLength(file.length()-20); 
} catch (IOException x) { 
    System.err.println(x); 
} finally { 
    if (file != null) file.close(); 
} 
+0

嗨, 感謝您的回覆。是否有任何方法可以部分刪除文件內容意味着從特定偏移量開始計數並刪除? – 2010-04-12 13:11:34

3
new FileOutputStream(file, false).close(); 
1

可能問題是這隻留下頭部我認爲而不是尾巴?

public static void truncateLogFile(String logFile) { 
    FileChannel outChan = null; 
    try { 
     outChan = new FileOutputStream(logFile, true).getChannel(); 
    } 
    catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     System.out.println("Warning Logfile Not Found: " + logFile); 
    } 

    try { 
     outChan.truncate(50); 
     outChan.close(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
     System.out.println("Warning Logfile IO Exception: " + logFile); 
    } 
} 
0
try { 
     PrintWriter writer = new PrintWriter(file); 
     writer.print(""); 
     writer.flush(); 
     writer.close(); 

    }catch (Exception e) 
    { 

    } 

此代碼將刪除「文件」的當前內容,並設置文件爲0