Ad space (banner)
โ˜•Java Lessons
Lesson 52 / 68

File Reading and Writing Basics

This lesson covers the basics of reading and writing files in Java, so a program can save and load a text file. It's for anyone searching "Java Files.writeString usage."

Files.writeString() writes to a file, and Files.readString() reads one. A basic operation used constantly in real work โ€” saving a config file or a log, for example.

The example saves memo content to a file with Files.writeString(Paths.get("memo.txt"), ...), then reads the same file and displays its content with Files.readString(...). This is a relatively concise file-handling API added in Java 11 and later.

A common early mistake is not accounting for the possibility that file operations can throw an exception. You need to declare throws Exception or wrap it in try-catch โ€” forgetting either produces a compile error.

In real projects, using the asynchronous version of the API lets you handle reading and writing large files more efficiently.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Java directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)