gpt4 book ai didi

java - 如何写入文本文件

转载 作者:行者123 更新时间:2023-12-02 07:01:39 24 4
gpt4 key购买 nike

我的方法已准备就绪,但它只是没有按照预期将重复项写入我的文本文件,而是打印到屏幕上,但不打印到文件中?

// Open the file.
File file = new File("file.txt");
Scanner inputFile = new Scanner(file);
//create a new array set Integer list
Set<Integer> set = new TreeSet<Integer>();
//add the numbers to the list
while (inputFile.hasNextInt()) {
set.add(inputFile.nextInt());
}
// transform the Set list in to an array
Integer[] numbersInteger = set.toArray(new Integer[set.size()]);
//loop that print out the array
for(int i = 0; i<numbersInteger.length;i++) {
System.out.println(numbersInteger[i]);
}
for ( int myDuplicates : set) {
System.out.print(myDuplicates+",");
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
duplicates.write(myDuplicates + System.getProperty("line.separator"));
} catch (IOException e) {
System.out.print(e);
duplicates.close();
}
//close the input stream
inputFile.close();
}
}

这部分就是我正在谈论的部分

for ( int myDuplicates : set) {
System.out.print(myDuplicates+",");
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
duplicates.write(myDuplicates + System.getProperty("line.separator"));
} catch (IOException e) {
System.out.print(e);
duplicates.close();
}
//close the input stream
inputFile.close();
}
}

最佳答案

只有在出现 IOException 时,您才会调用 duplicates.close()。如果不关闭写入器,则不会将任何缓冲数据刷新到其中。您应该在finally block 中关闭编写器,以便无论是否存在异常都可以关闭它。

但是,您应该在循环之外打开和关闭文件。您希望文件在整个循环中保持打开状态。您可能想要:

BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
// Loop in here, writing to duplicates
} catch(IOException e) {
// Exception handling
} finally {
try {
duplicates.close();
} catch (IOException e) {
// Whatever you want
}
}

如果您使用的是 Java 7,则可以使用 try-with-resources 语句更简单地完成此操作。

(此外,由于某种原因,您在循环中调用 inputFile.close() ,距离您实际完成读取数英里之后。同样,这应该位于 finally block ,当您不再需要 inputFile 时。)

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

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