File truncate operation in Java

后端 未结 7 1841
清酒与你
清酒与你 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条回答
  •  旧时难觅i
    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);
    

提交回复
热议问题