How to delete only the content of a file in Java?

2020-02-12 05:47发布

How can I delete the content of a file in Java?

标签: java file
6条回答
在下西门庆
2楼-- · 2020-02-12 06:15
new FileOutputStream(file, false).close();
查看更多
3楼-- · 2020-02-12 06:18

You could do this by opening the file for writing and then truncating its content, the following example uses 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: truncate just the last 20 bytes of the file:

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(); 
} 
查看更多
放我归山
4楼-- · 2020-02-12 06:24
try {
        PrintWriter writer = new PrintWriter(file);
        writer.print("");
        writer.flush();
        writer.close();

    }catch (Exception e)
    {

    }

This code will remove the current contents of 'file' and set the length of file to 0.

查看更多
疯言疯语
5楼-- · 2020-02-12 06:32

Open the file for writing, and save it. It delete the content of the file.

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2020-02-12 06:33

How about this:

new RandomAccessFile(fileName).setLength(0);
查看更多
▲ chillily
7楼-- · 2020-02-12 06:33

May problem is this leaves only the head I think and not the tail?

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);
    }
}
查看更多
登录 后发表回答