File truncate operation in Java

后端 未结 7 1355
清酒与你
清酒与你 2020-11-29 11:02

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(Fil         


        
相关标签:
7条回答
  • 2020-11-29 11:31

    Use Apache Commons IO API:

        org.apache.commons.io.FileUtils.write(new File(...), "", Charset.defaultCharset());
    
    0 讨论(0)
  • 2020-11-29 11:37

    It depends on how you're going to write to the file, but the simplest way is to open a new FileOutputStream without specifying that you plan to append to the file (note: the base FileOuptutStream constructor will truncate the file, but if you want to make it clear that the file's being truncated, I recommend using the two-parameter variant).

    0 讨论(0)
  • 2020-11-29 11:40

    One liner using Files.write()...

    Files.write(outFile, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
    

    Can use File.toPath() to convert from File to Path prior as well.

    Also allows other StandardOpenOptions.

    0 讨论(0)
  • 2020-11-29 11:42

    Use FileChannel.truncate:

    try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
      outChan.truncate(newSize);
    }
    
    0 讨论(0)
  • 2020-11-29 11:47

    RandomAccessFile.setLength() seems to be exactly what's prescribed in this case.

    0 讨论(0)
  • 2020-11-29 11:48

    Use RandomAccessFile#read and push the bytes recorded in this way into a new File object.

    RandomAccessFile raf = new RandomAccessFile(myFile,myMode);  
    byte[] numberOfBytesToRead = new byte[truncatedFileSizeInBytes];  
    raf.read(numberOfBytesToRead);    
    FileOutputStream fos = new FileOutputStream(newFile);  
    fos.write(numberOfBytesToRead);
    
    0 讨论(0)
提交回复
热议问题