public void readLines(File file) throws IOException {
try (BufferedSource bufferedSource = Okio.buffer(Okio.source(file))) {
for (String line; (line = bufferedSource.readUtf8Line()) != null; ) {
System.out.println(line);
}
}
}
try-with-source
是jdk1.7开始提供的语法糖,在try
语句()里面的资源对象,jdk最终会自动调用它的close
方法去关闭它, 即便try
里有多个资源对象也是可以的,这样就不用你手动去关闭资源了。但是在android里面使用的话,会提示你要求API level最低为19
才可以。
readUtf8Line()
方法适用于大多数文件。对于某些用例,还可以考虑使用readUtf8LineStrict()
。类似readUtf8Line()
,但它要求每一行都以\n
或\r\n
结尾。如果在这之前遇到文件结尾,它将抛出一个EOFException
。它还允许设置一个字节限制来防止错误的输入。
public void readLines(File file) throws IOException {
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
while (!source.exhausted()) {
String line = source.readUtf8LineStrict(1024L);
System.out.println(line);
}
}
}
写文本文件
public void writeEnv(File file) throws IOException {
Sink fileSink = Okio.sink(file);
BufferedSink bufferedSink = Okio.buffer(fileSink);
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
bufferedSink.writeUtf8(entry.getKey());
bufferedSink.writeUtf8("=");
bufferedSink.writeUtf8(entry.getValue());
bufferedSink.writeUtf8("\n");
}
bufferedSink.close();
}
类似于读文件使用Source
和BufferedSource
, 写文件的话,则是使用的Sink
和 BufferedSink
,同样的在BufferedSink
接口中也提供了丰富的接口方法:
其中Okio.buffer(fileSink)
内部返回的实现对象是一个RealBufferedSink
类的对象, 跟RealBufferedSource
一样它也是一个装饰者对象,具备Buffer
缓冲功能。同样,以上代码可以使用jdk的try-with-source
语法获得更加简便的写法:
public void writeEnv(File file) throws IOException {
try (BufferedSink sink = Okio.buffer(Okio.sink(file))) {
sink.writeUtf8(“啊啊啊”)
.writeUtf8("=")
.writeUtf8(“aaa”)
.writeUtf8("\n");
}
}
其中的换行符\n
,Okio没有提供单独的api方法,而是要你手动写,因为这个跟操作系统有关,不过你可以使用System.lineSeparator()
来代替\n
,这个方法在Windows上返回的是"\r\n"
在UNIX上返回的是"\n"。
在上面的代码中,对writeUtf8()
进行了四次调用, 这样要比下面的代码更高效,因为虚拟机不必对临时字符串进行创建和垃圾回收。
sink.writeUtf8(entry.getKey()