gpt4 book ai didi

java - 将数据写回二进制文件

转载 作者:行者123 更新时间:2023-11-30 04:24:35 24 4
gpt4 key购买 nike

我正在尝试将字符、 double 和整数写回基于字符串数组列表的二进制文件。但是,在完成写入并再次读取二进制文件后,它会生成错误。任何人都可以帮忙解决这个问题,我真的很感激。

ArrayList<String>temp = new ArrayList<String>();
for(int i = 0;i<temp.size();i++){
String decimalPattern = "([0-9]*)\\.([0-9]*)";
boolean match = Pattern.matches(decimalPattern, temp.get(i));
if(Character.isLetter(temp.get(i).charAt(0))){
os.writeChar(temp.get(i).charAt(0));
}
else if(match == true){
Double d = Double.parseDouble(temp.get(i));
os.writeDouble(d);
}
else
{
int in = Integer.parseInt(temp.get(i));
os.writeInt(in);
}
}
os.close();
}

最佳答案

这是一个非常简单的示例,将向您展示如何按顺序读取您的数据:

public void readFile(String absoluteFilePath){
ByteBuffer buf = ByteBuffer.allocate(2+4+8) // creating a buffer that is suited for data you are reading
Path path = Paths.get(absoluteFilePath);

try(FileChannel fileChannel = (FileChannel)Files.newByteChannel(path,Enum.setOf(READ))){
while(true){
int bytesRead = fileChannel.read(buf);
if(bytesRead==-1){
break;
}
buf.flip(); //get the buffer ready for reading.
char c = buf.asCharBuffer().readChar(); // create a view buffer and read char
buf.position(buf.position() + 2); //now, lets go to the int
int i = buf.asIntBuffer().readInt(); //read the int
buf.position(buf.position()+ 4); //now, lets go for the double.
double d = buf.asDoubleBuffer().readDouble();
System.out.println("Character: " + c + " Integer: " + i + " Double: " + d);
buf.clear();
}
}catch(IOException e){
e.printStackTrace();
}// AutoClosable so no need to explicitly close
}
<小时/>

现在,假设您始终将数据以 (char,int,double) 形式写入文件中,并且您的数据不会出现乱序或不完整的情况,如 (char,int)/(char,double) ,您可以通过指定文件中的位置(以字节为单位)来随机读取数据,从何处获取数据:

channel.read(byteBuffer,position);  

在您的情况下,数据大小始终为 14 字节,即 2 + 4 + 8,因此所有读取位置都将是 14 的倍数。

First block at: 0 * 14 = 0  
Second block at: 1 * 14 = 14
Third block at: 2 * 14 = 28

等等..

enter image description here

与阅读类似,您也可以使用

进行书写
channel.write(byteBuffer,position)  

同样,位置将是 14 的倍数。

这适用于 FileChannel 的情况,它是 ReadableByteChannel 的父类(super class),它是用于读取的专用 channel ,WritableByteChannel 是是一个用于写入的专用 channel ,而 SeekableByteChannel 既可以进行读取也可以进行写入,但稍微复杂一些。

使用 channel 和 ByteBuffer 时,请注意读取方式。没有什么可以阻止我将 14 个字节作为一组 7 个字符读取。虽然这看起来很可怕,但这为您提供了读写数据的完全灵 active

关于java - 将数据写回二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16255490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com