We’ve written some recipes that demonstrate how to solve common problems with Okio. Read through them to learn about how everything works together. Cut-and-paste these examples freely; that’s what they’re for.
These recipes work on all platforms: Java, Android, Kotlin/Native, and Kotlin/JS. See [java.io Recipes](https://square.github.io/okio/java_io_recipes/) for samples that integrate Java APIs.
Use FileSystem.source(Path) to open a source stream to read a file. The returned Source interface is very small and has limited uses. Instead we wrap the source with a buffer. This has two benefits:
- **It makes the API more powerful.** Instead of the basic methods offered by `Source`, `BufferedSource` has dozens of methods to address most common problems concisely.
- **It makes your program run faster.** Buffering allows Okio to get more done with fewer I/O operations.
Each `Source` that is opened needs to be closed. The code that opens the stream is responsible for making sure it is closed.
每个被打开的Source都需要被关闭。打开流的代码要负责确保它被关闭。
public void readLines(Path path) throws IOException {
try (Source fileSource = FileSystem.SYSTEM.source(path);
BufferedSource bufferedFileSource = Okio.buffer(fileSource)) {
while (true) {
String line = bufferedFileSource.readUtf8Line();
if (line == null) break;
if (line.contains("square")) {
System.out.println(line);
}
}
}
}
???+ 原文
The `readUtf8Line()` API reads all of the data until the next line delimiter – either `\n`, `\r\n`, or the end of the file. It returns that data as a string, omitting the delimiter at the end. When it encounters empty lines the method will return an empty string. If there isn’t any more data to read it will return null.
The `readUtf8Line()` method is suitable for parsing most files. For certain use-cases you may also consider `readUtf8LineStrict()`. It is similar but it requires that each line is terminated by `\n` or `\r\n`. If it encounters the end of the file before that it will throw an `EOFException`. The strict variant also permits a byte limit to defend against malformed input.
Above we used a `Source` and a `BufferedSource` to read a file. To write, we use a `Sink` and a `BufferedSink`. The advantages of buffering are the same: a more capable API and better performance.
There isn’t an API to write a line of input; instead we manually insert our own newline character. Most programs should hardcode `"\n"` as the newline character. In rare situations you may use `System.lineSeparator()` instead of `"\n"`: it returns `"\r\n"` on Windows and `"\n"` everywhere else.