gpt4 book ai didi

java - writeArray 二进制文件未在 readArray 中显示完整数组

转载 作者:行者123 更新时间:2023-11-30 02:00:51 25 4
gpt4 key购买 nike

我有两个类(writeArray 和 readArray),它们应该写入一个 {10, 20, 30} 数组并在演示类中打印它,但它只打印出 10,没有 20 或 30,而且我不打印了解它是否没有读取整个数组或者我的演示代码是否存在问题。

这是数组类:

  import java.io.*;

public class FileArray{
public static void writeArray(){
String fileName = "file.bin";
int[] array = {10, 20, 30};

try{
FileOutputStream fileOs = new FileOutputStream(fileName);
DataOutputStream os = new DataOutputStream(fileOs);

for (int i = 0; i < 3; i++)
os.writeInt(array[i]);

os.close();
fileOs.close();
}

catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readArray(){
String fileName = "file.bin";
int[] array1;

try{
FileInputStream fileIs = new FileInputStream(fileName);
DataInputStream is = new DataInputStream(fileIs);

System.out.println(is.readInt());

is.close();
fileIs.close();
}

catch (FileNotFoundException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

这是显示类:

  public class FileArrayDemo {
public static void main(String[] args){
FileArray write = new FileArray();
write.writeArray();

System.out.println("Done writing. Now reading.");

FileArray read = new FileArray();
read.readArray();

}
}

最佳答案

您只读取一个int。相反,您应该循环直到到达 EOF:

while (true) {
try {
System.out.println(is.readInt());
} catch (EOFException e) {
// Reached the end of the file, break out the loop
break;
}
}

关于java - writeArray 二进制文件未在 readArray 中显示完整数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899980/

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