gpt4 book ai didi

java - 如何写入和读取dat文件

转载 作者:行者123 更新时间:2023-12-01 11:11:13 25 4
gpt4 key购买 nike

Write a program that asks the user to enter whole numbers (they enter –1 to finish data entry). The numbers are to be written to a binary file. This is to be done in a method called writeBinaryFile(). Then the program should read the numbers from the binary file and display them to the console. This should be done in a method called readBinaryFile(). The main() method should just call writeBinaryFile() then readBinaryFile().

到目前为止我的代码:

public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Please enter whole numbers then enter -1 to data entry.");
writeBinaryFile();
readBinaryFile();
}

/**
* This method opens a binary file and writes the contents
* of an int array to the file.
*/
private static void writeBinaryFile() throws IOException, FileNotFoundException
{
Scanner input = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<Integer>();
try
{
FileOutputStream output = new FileOutputStream("Files//Numbers.dat");
int numbers = 0;

while(numbers != -1)
{
number.add(numbers = input.nextInt());

output.write(numbers);
}
output.close();
}
catch(IOException ex)
{
ex.getMessage();
}
}

private static void readBinaryFile() throws IOException
{
FileInputStream input = new FileInputStream("Files//Numbers.dat");
int value;
value = input.read();
System.out.print("The numbers in the file are: ");
try
{
while(value != -1)
{
System.out.print(value +" ");
value = input.read();
}
input.close();
}
catch(IOException ex)
{
ex.getMessage();
}
}

问题是当我输入这些数据时:

5 2 4 6 8 4 -1

我的输出是:

5 2 4 6 8 4 255

如何阻止 255 出现?

最佳答案

您应该避免在输入中添加 -1。问题出在一行:number.add(numbers = input.nextInt()); 循环中。

编辑:要写入二进制数据,您应该使用DataInputStream/DataOutputStream。您不能将其与 Scanner 混合使用,因为它主要用于文本数据。一个示例是:

public static void main(String[] args) throws IOException {
writeNumbers();
readNumbers();
}

private static void writeNumbers() throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("C://Numbers.dat"));
for (int i = 0; i < 10; i++) {
output.writeInt(i);
System.out.println(i);
}
output.close();
}

private static void readNumbers() throws IOException{
DataInputStream input = new DataInputStream(new FileInputStream("C://Numbers.dat"));
while (input.available() > 0) {
int x = input.readInt();
System.out.println(x);
}
input.close();
}

关于java - 如何写入和读取dat文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32345371/

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