繁体   English   中英

如何写入文本文件

[英]How do I write to a text file

我的方法都准备就绪,但它只是没有将重复项写入我的文本文件,因为它打算做,它打印到屏幕但不打印到文件?

// 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块中关闭编写器,以便关闭它是否存在异常。

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

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() ,在你实际读完它之后的里程数。再次,当你不再需要inputFile时,这应该在finally块中。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM