My goal is to read and write formatted strings to a file. I'm actually using PrintWriter class for output and Scanner for input.
Code:
PrintWriter out = null;
Scanner in = null;
File file = new File(System.getProperty("user.dir")+"/data/level1/grounds.txt");
try {
out = new PrintWriter(file);
} catch (FileNotFoundException e) { e.printStackTrace(); }
out.println("foo");
try {
in = new Scanner(file);
} catch (FileNotFoundException e) { e.printStackTrace(); }
System.out.println(in.nextLine());
in.close();
The file is created, but in.nextLine() throws a NoSuchElementException: no line found . After the execution (terminated by this exception) the file is blank.
Please leave a suggestion about how to do it correctly.
完成所有写入操作后,应关闭输出打印机,以使其反映在扫描仪中。
This is because out.println("foo");
writes in the PrintWriter
but not on the file, you need to flush()
to have the content on the file, you may close()
also (this will automatically flush()
Simple flush
out.println("foo"); out.flush()
Close to flush
out.println("foo"); out.close()
Use an auto-flush PrintWriter
out = new PrintWriter(new FileOutputStream(file), true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.