Skip to content

Text files

Java for AP CS A Lesson 16 1:38 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
PrintWriter writes to a file with the same println you already know. PrintWriter 用你已经熟悉的 println 往文件里写东西。
But there is one line people forget, and it costs everything. 但有一行大家总是漏掉,而漏掉它就前功尽弃。
Leave out close and nothing reaches the disk — the file is empty even though the program ran without an error. 不写 close,什么都到不了磁盘上—— 程序一点错都没报,文件却是空的。
Close it and everything lands. 把它 close 掉,东西才真正落下去。
Anything to do with files can fail, so the method also has to say throws IOException. 任何和文件打交道的操作都可能失败, 所以方法还得写上 throws IOException。
Reading uses Scanner, the same class you use for keyboard input, but pointed at a File. 读取用的是 Scanner——就是你用来读键盘输入的那个类,只不过对准了一个 File。
And it always comes in pairs: hasNextInt asks whether there is another number, and only then does nextInt take it. 而它总是成对出现: hasNextInt 先问"还有没有下一个数字", 问过之后才由 nextInt 把它取走。
Without that guard, you keep taking past the end of the file, and the end of the file throws. 没有这层守卫,你就会一直取到文件末尾之外, 而文件末尾会抛异常。
The same shape reads whole lines instead of numbers: hasNextLine, then nextLine, one line at a time until the file runs out. 同样的形状,可以按"整行"来读而不是按数字: hasNextLine,然后 nextLine,一次一行,直到文件读完。
That is worth noticing — every reading loop in this course is the same two methods, hasNext-something, then next-something. 这一点值得留意—— 这门课里每一个读取循环,都是同样的两个方法: 先 hasNext 什么,再 next 什么。
Four things to take with you. 带走四点。
One: file methods throw, so declare throws IOException. 第一:文件方法会抛异常,所以要声明 throws IOException。
Two: PrintWriter writes, and close is what saves it. 第二:PrintWriter 负责写,而 close 才是真正把它保存下来的那一步。
Three: Scanner reads a File, one value at a time. 第三:Scanner 读文件,一次取一个值。
Four: always ask hasNext before you take next. 第四:取 next 之前,永远先问 hasNext。
Now write and read a file in the task below. 现在去下面的题里写一个文件再把它读回来。

Log in or create account

IGCSE, A-Level & AP