Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

File truncate operation in Java

What is the best-practice way to truncate a file in Java? For example this dummy function, just as an example to clarify the intent:

void readAndTruncate(File f, List<String> lines)
        throws FileNotFoundException {
    for (Scanner s = new Scanner(f); s.hasNextLine(); lines.add(s.nextLine())) {}

    // truncate f here! how?

}

The file can not be deleted since the file is acting as a place holder.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use FileChannel.truncate:

try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
  outChan.truncate(newSize);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...