用Java删除文件内容

时间:2009-04-29 05:28:48

标签: java io

我正在向temp.fls文件写入字节。完成操作后,我想从temp.fls文件中删除最后256个字节。我怎样才能做到这一点?请帮帮我。

提前致谢。

2 个答案:

答案 0 :(得分:10)

像这样使用RandomAccessFile.setLength()

RandomAccessFile f = new RandomAccessFile(yourFile,"rw");
f.setLength(f.length()-256);

答案 1 :(得分:0)

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileDemo {

    public static void main(String ... args) throws FileNotFoundException, IOException
    {
        File file = new File(<FILE_PATH>);
         System.err.println("MSR:: RandomAccessFileDemo :: the target length is"+file.length());
        RandomAccessFile raf = new RandomAccessFile(file,"rwd");
        raf.seek(file.length()-1); // Set the pointer to the end of the file
        System.err.println("MSR:: RandomAccessFileDemo :: the file pointer is"+raf.getFilePointer());

        raf.setLength(raf.length()-raf.length());

    }
}