java - 将值为 y 的 x 个字节写入 java 中的文件

标签 java io

我正在尝试将一定数量的字节写入文件,比如 x 字节,值为 y。问题是我做了很多时间,我目前正在使用 DataOutputStream 和 BufferedOutputStream 以及获取字节数组的 write 方法。每次我分配一个新的长度为 x 的字节数组并写入它。这很浪费,我想知道是否有更有效的方法? 谢谢。

编辑:我通过分配一个按需增长的大数组来实现它,但问题是我存储它并且它可能变得非常大。 代码:

 byte[] block = new byte[4096];
    try {
        for(int i=0; i<nameOccurence.length; ++i){
            if(nameOccurence[i] >= block.length){
                int size = ((Integer.MAX_VALUE - nameOccurence[i]) <= 0.5*Integer.MAX_VALUE) ? Integer.MAX_VALUE : (nameOccurence[i] * 2);
                block = new byte[size];
            }
            if(nameOccurence[i] == 0){
                namePointer[i] = -1;//i.e. there are no vertices with this name
                continue;
            }
            namePointer[i] = byteCounter;

            ds.writeInt(nameOccurence[i]);
            ds.write(block, 0, nameOccurence[i]*2);
            ds.write(block, 0, nameOccurence[i]*2);
            byteCounter += (4*((long)nameOccurence[i]))+4;//because we wrote an integer.
        }

其中 ds 是数据输出流。请注意,如果 nameOccurence[i] 足够大,数组 block 可以增长到 max int。

我认为最好的方法是找到 nameOccurence 中所有 i 的最大数量并分配这个长度的数组。问题是它可以获得 Integer.MAX_VALUE。

也许循环运行并每次写入1个字节会更好?请注意DataOuputStream的底层是BufferedOutputStream。

最佳答案

使用

String strFileName = "C:/FileIO/BufferedOutputStreamDemo";
FileOutputStream fos = new FileOutputStream(strFileName);
fos.write(yourbytes);

关于java - 将值为 y 的 x 个字节写入 java 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5867297/

相关文章:

python - 通过Python写入/etc/hosts时IOError : 13, 'Permission denied'

java - 当我保存对象时,我无法从任务加载

java - 是否可以使用java方法返回 "if condition satisfies return a list else return an error message"

python - 在 C 语言中,如何在用户输入的末尾连接 .txt?

c - 在 C 中分割文件中的二进制文件而不会损坏

python - 在 Python 中将列表转换为列

java - 将字符串转换为 RTF 格式

javax websocket客户端ssl连接

与正则表达式匹配的java字符串

java - 解析 JDOM 中的 XML 文件以获取子子节点