我已經使用RandomAccessFile
創建了一個具有預分配大小的文件。但是當我使用FileOutputStream
來寫入文件時,它正在改變文件的大小。有沒有什麼辦法阻止這種使用FileOutputStream
FileOutputStream將文件大小減小到0
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
public class testFileSize {
public static class Status implements Serializable {
}
public static void preAllocate(String path, long maxSize, boolean preAllocate)
throws IOException {
RandomAccessFile raf = new RandomAccessFile(path, "rw");
try {
raf.setLength(maxSize);
} finally {
raf.close();
}
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FileOutputStream fileOutput = null;
ObjectOutputStream objectOutput = null;
try {
final File f = new File("/tmp/test.bin");
preBlow(f.getAbsolutePath(), 2048, false);
Status s = new Status();
fileOutput = new FileOutputStream(f);
objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(new Status());
objectOutput.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
objectOutput.close();
fileOutput.close();
}
}
}
提示:閱讀fileou的Javadoc tputstream並查看可用的構造函數。 –