簡體   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