2013-05-16 52 views
0

我已经准备好了我的方法,但它并没有像我们的文本文件那样将重复项写入文本文件,而是将其打印到屏幕上而不是文件中?如何写入文本文件

// 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(); 
     } 
} 

回答

2

你只是调用duplicates.close()如果有一个IOException。如果你没有关闭作者,你不会将任何缓冲的数据清空。您应该关闭finally区块中的作者,以便关闭它,无论是否有例外。

但是,您应该打开和关闭文件以外的循环。你希望文件在循环中打开。您可能想要:

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块,当你不再需要inputFile

+0

现在它只向文件中写入1个数字 –

+0

@WagnerMaximiliano:您应该在循环外打开并关闭它。将编辑的答案说清楚。 –

+0

我其实非常感谢 –