如何写入文本文件

时间:2013-05-16 21:31:29

标签: 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 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();
      }
}

1 个答案:

答案 0 :(得分: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。)