Java 如何写入文本文件
我已经准备好了我的方法,但它只是没有像它想做的那样将副本写入我的文本文件,而是打印到屏幕上,而不是文件上Java 如何写入文本文件,java,duplicates,text-files,Java,Duplicates,Text Files,我已经准备好了我的方法,但它只是没有像它想做的那样将副本写入我的文本文件,而是打印到屏幕上,而不是文件上 // 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 num
// 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();
}
}
如果存在
IOException
,则只调用duplicates.close()
。如果不关闭写入程序,则不会刷新任何缓冲数据。您应该在finally
块中关闭writer,这样无论是否存在异常都可以关闭它
但是,您应该在循环之外打开和关闭文件。您希望文件在整个循环中处于打开状态。您可能想要:
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
}
}
如果您使用的是Java7,那么可以使用try with resources语句更简单地实现这一点
(另外,由于某种原因,您在循环中调用了
inputFile.close()
,距离您实际读取完它已经有几英里了。同样,当您不再需要inputFile
时,这应该在finally
块中)@WagnerMaximiliano:您应该在循环外打开和关闭它。将编辑答案以使其清晰。
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
}
}