[英]Java (Read and write to file)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class backup {
public static void main(String[] args) {
System.out.println("\nThe names in the file are:\n");
readFromFile();
}
public static void readFromFile() {
try {
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt");
Scanner input = new Scanner(System.in);
while (file.hasNext()) {
String name = file.nextLine();
System.out.printf("Please enter " + name + "'s mark:");
int mark = input.nextInt();
Scanner kybd = new Scanner(System.in);
{
if (mark >= 40) {
// System.out.println(name + " has passed");
pass.println(name);
} else {
// System.out.println(name + " has failed");
fail.println(name);
}
}
} // end while
} // end try
catch (IOException ioe) {
System.out.println("Error handling file");
} // end catch
}// readFromFile
}
如果用戶得分超過40,則他們無法寫入文件通行證並且失敗,如果用戶進入通行證,則名稱文件只是一個名稱列表,但是我無法獲取txt文件來填充輸出。
當我在一段時間內插入我的打印機時,只有最后一個條目被添加到通過或失敗的txt文件中。
PrintWriter
僅在它們關閉( close
)或刷新( flush
或可能認為它是時候;-)時才真正寫入。
盡可能嘗試使用try-with-resources ,這樣您就不必考慮關閉/刷新流或編寫器。 嘗試與-資源需要照顧AutoClosable
-implementations是在結束自動關閉try
-塊。
您的示例用try-with-resources重寫(僅顯示初始部分):
try(
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt")
) {
其余的可以保留原樣...或者,如果您願意:您可能還想查找Files-API 。 也許使用Files.lines
適合您?
您應該在文件上調用函數close
,以將其寫入dsisk。
否則,您的修改僅在內存中
類似於: file.close()
如果使用PrintWriter
,則必須最后close
流。 否則,它將僅在內存中。 嘗試這個:
try {
Scanner file = new Scanner(new File("Names.txt"));
PrintWriter pass = new PrintWriter("pass.txt");
PrintWriter fail = new PrintWriter("fail.txt");
Scanner input = new Scanner(System.in);
while (file.hasNext()) {
String name = file.nextLine();
System.out.printf("Please enter " + name + "'s mark:");
int mark = input.nextInt();
//Scanner kybd = new Scanner(System.in);
//{
if (mark >= 40) {
// System.out.println(name + " has passed");
pass.println(name);
} else {
// System.out.println(name + " has failed");
fail.println(name);
}
//}
} // end while
pass.close();
fail.close();
} // end try
catch (IOException ioe) {
System.out.println("Error handling file");
}
您需要確保在末尾添加一個finally塊,並在可關閉的任何對象上調用close方法,因此在這種情況下,請在printwriter上。 在這種情況下,pass.close()和fail.close()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.