如何创建特定大小的二进制文件?

时间:2012-06-11 18:32:35

标签: java file

如何使用Java创建一个大小为250KB的二进制文件和另一个1MB的二进制文件? 有可能吗?

3 个答案:

答案 0 :(得分:6)

 new RandomAccessFile("file.file", "rw").setLength(1048576);

答案 1 :(得分:1)

FileOutputStream s = new FileOutputStream("a.bin");
byte[] buf = new byte[250*1024];
s.write(buf);
s.flush();
s.close();

答案 2 :(得分:0)

     public voidwriteFile(String path, int bytes) throws Exception {
    OutputStream outputStream = null;
    File f=null;
    try {
        f = new File(path + "/tmp.txt");
        f.createNewFile();
        byte[] buf = new byte[bytes];
        outputStream = new BufferedOutputStream(new FileOutputStream(f));
        outputStream.write(buf);
        outputStream.flush();
    } catch (Exception e) {
        throw new Exception();
    } finally {
        try {
            if(f!=null){
                f.delete();
            }
            outputStream.close();
        } catch (IOException e) {
        }
    }
}