@linux1s1s
2016-11-22T14:04:46.000000Z
字数 1777
阅读 2245
AndroidRefine
2016-11
系列博文
Android 开源库 - OkHttp
Android 开源库 - Retrofit
Android 开源库 - Okio
Android 开源库 - Fresco
Okio 补充了 java.io 和 java.nio 的内容,使得数据访问、存储和处理更加便捷。
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import okio.Sink;
import okio.Source;
public class OkioUtil {
private static final String FILE_NAME = Environment.getExternalStorageDirectory() + "/okio/dest.txt";
private OkioUtil() {
//Do Nothing
}
/**
* 写入本地文件
*
* @param content
* @return
*/
public static boolean writeLocalFile(String content) {
if (TextUtils.isEmpty(content))
return false;
Sink sink = null;
BufferedSink bufferedSink = null;
File file = new File(FILE_NAME);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e(MainActivity.TAG, "new File(FILE_NAME) failed");
return false;
}
}
try {
sink = Okio.sink(file);
bufferedSink = Okio.buffer(sink);
bufferedSink.writeUtf8(content);
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
closeQuietly(bufferedSink);
closeQuietly(sink);
}
return true;
}
/**
* 读出本地文件
*
* @return
*/
public static String readLocalFile() {
Source source = null;
BufferedSource bufferedSource = null;
File file = new File(FILE_NAME);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e(MainActivity.TAG, "new File(FILE_NAME) failed");
return null;
}
}
try {
source = Okio.source(file);
bufferedSource = Okio.buffer(source);
return bufferedSource.readUtf8();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeQuietly(bufferedSource);
closeQuietly(source);
}
return null;
}
private static void closeQuietly(Closeable closeable) {
if (closeable == null)
return;
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
参考文章:
OkHttp GitHub Doc
Retrofit GitHub DocR Doc
Fresco GitHub Doc
Okio GitHub Video
更多请参考拆轮子系列:拆 Okio