gpt4 book ai didi

java - 文件的输入/输出

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

我为我的一个类(class)编写了一个简短的程序,但有些东西我无法弄清楚。所以我应该在文件中写入 100 个随机整数,读回数据并按升序打印整数。一切正常,但我在输出文件上看不到最终的排序列表,任何人都可以看到为什么吗?

这是我的代码:

private final static int NUMBEROFRANDOM = 100;

public static void main(String[] args) throws IOException {

// Creating my file
java.io.File file = new java.io.File("Question1.txt");

// If it already exists, print a message and terminate program
if (file.exists()) {
System.out.println("File already exists.");
System.exit(0);
}

// Creating my PrintWriter object
PrintWriter output = new PrintWriter(file);

// Creating 100 random numbers between 0 and 100 and printing them on the file
for (int i = 0; i < NUMBEROFRANDOM; i++) {
int number = (int) (Math.random() * 101);
output.print(number + " ");
}

// Creating my Scanner object
Scanner input = new Scanner(file);

// Creating my array list to store the sorted list of 100 elements
ArrayList<Integer> sortedList = new ArrayList<Integer>();

// Reading the elements from the file and adding them into my array list
while (input.hasNext()) {
sortedList.add(input.nextInt());
}

//Sorting elements from array list
Collections.sort(sortedList);

// Printing the elements in increasing order
for (int i = 0; i < sortedList.size(); i++) {
//System.out.println(sortedList.get(i));
output.print(sortedList.get(i));
}

// Closing my objects
input.close();
output.close();

}

非常感谢,非常感谢您的帮助!

最佳答案

使用 Scanner input = new Scanner(file); 读取文件时,文件为空

在打印值后使用output.flush()保存数据。

output.close() - 将关闭您的流,并且您将无法存储排序后的值。

// Creating 100 random numbers between 0 and 100 and printing them on the file
for (int i = 0; i < NUMBEROFRANDOM; i++) {
int number = (int) (Math.random() * 101);
output.print(number + " ");
}

output.flush();

关于java - 文件的输入/输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43094364/

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