正在尝试从二进制文件读取到数组



我正在做一份学校作业,要求如下:"设计一个具有名为writeArray的静态方法的类。该方法应该有两个参数:文件名和对int数组的引用。该文件应作为二进制文件打开,数组的内容应写入该文件,然后关闭该文件。在名为readArray的类中编写第二个方法。该方法应该有两个参数:文件名和对int数组的引用。应该打开文件,从文件中读取数据并将其存储在数组中,然后关闭文件。在程序中演示这两种方法">

到目前为止,这是我的课堂和演示代码:

import java.io.*;
public class FileArray
{

public static void writeArray(String filename, int[] array) throws IOException
{
//Open the file.
DataOutputStream outputFile = new DataOutputStream(new FileOutputStream("MyNumbers.txt"));

//Write the array.
for(int index = 0; index < array.length; index++)
{
outputFile.writeInt(array[index]);
}

//Close the file.
outputFile.close();
}
public static void readArray(String filename, int[] array) throws IOException
{
int number;
boolean endOfFile = false;

//Open the file.
FileInputStream fstream = new FileInputStream("MyNumbers.txt");
DataInputStream inputFile = new DataInputStream(fstream);

//Read values from the array.
while (!endOfFile)
{
try
{
number = inputFile.readInt();
}
catch (EOFException e)
{
endOfFile = true;
}
}

//Close the file.
inputFile.close();
}
}

二等:

import java.io.*;
public class FileArrayDemo extends FileArray
{
public static void main(String[] args)
{
//Create arrays.
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8};
int[] test = new int[8];

//Try/catch clause.
try
{
//Write the contents of the numbers array to the file MyNumbers.txt.
FileArray fileArray = new FileArray();
fileArray.writeArray("MyNumbers.txt", numbers);

//Read the contents of the file MyNumbers.txt into the test array.
fileArray.readArray("MyNumbers.txt", test);

//Display the numbers from the test array.
System.out.println("The numbers read from the file are:");
for (int i = 0; i < test.length; i++)
System.out.print(test[i] + " ");
}
catch (IOException e)
{
System.out.println("Error = " + e.getMessage());
}
}
}

当我尝试使用演示文件时,我的数组显示的是所有的0,而不是数字1-8。我根本不确定我在这里做错了什么。我一直在遵循我书中的示例,但它们只在一个类中提供演示,而没有创建执行写/读操作的方法的类。

您只需要修改传入参数的数组,您的readArray函数只是读取的,不修改数组。

试着用这个来增加你的readArray函数:

public static void readArray(String filename, int[] array) throws IOException{
int number;
boolean endOfFile = false;
//Open the file.
FileInputStream fstream = new FileInputStream("MyNumbers.txt");
DataInputStream inputFile = new DataInputStream(fstream);
//Read values from the array.
int i = 0;
while (!endOfFile){
try{
number = inputFile.readInt();
array[i] = number;
i++;

}catch (EOFException e)
{
endOfFile = true;
}
}
//Close the file.
inputFile.close();
}

结果:

The numbers read from the file are:
1 2 3 4 5 6 7 8