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

1 回答 1

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。)

于 2013-05-16T21:36:13.310 回答