在文件中写入特定的字节数

时间:2014-11-21 17:50:04

标签: java

我有下面列出的数组:

我想在文件中写入这些字节,直到文件大小达到1029字节。有什么想法吗?

我尝试了这段代码,但它似乎不起作用:

public static byte[] aSnouty = {97, 98, 99, 100, 101, 102, 103, 104, 105, 49, 45, 50, 51, 52, 53};

File file = new File(filename);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    do {
        fos.write(aSnouty); 
    } while(file.length()!=1029);

} catch(Exception ex) {
    ex.printStackTrace();
}

1 个答案:

答案 0 :(得分:0)

以下是从您提供的代码开始的解决方案:

    byte[] aSnouty = {97, 98, 99, 100, 101, 102, 103, 104, 105, 49, 45, 50, 51, 52, 53};

    File file = new File("C:/users/BXM0121/testTenTwentyNine.txt");
    FileOutputStream fos = new FileOutputStream(file);
    int fileSizeInBytes = (int) file.length();
    final int maxFileSize = 1029;
    try {
        do {

            if ((maxFileSize - fileSizeInBytes) < aSnouty.length)
            {
                fos.write(Arrays.copyOfRange(aSnouty, 0, maxFileSize-fileSizeInBytes));
                break;
            }
            fos.write(aSnouty); 
            fileSizeInBytes += aSnouty.length;
        } while (file.length() != maxFileSize);

    } catch(Exception ex) {
        ex.printStackTrace();
    } finally{
        fos.close();
    }

编辑:我看到你对正态分布的评论,这是一个完全不同的野兽。我没有为此编码。

相关问题