[英]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.