[关闭]
@linux1s1s 2016-11-22T06:04:46.000000Z 字数 1777 阅读 2122

Android 开源库 - Okio

AndroidRefine 2016-11


系列博文
Android 开源库 - OkHttp
Android 开源库 - Retrofit
Android 开源库 - Okio
Android 开源库 - Fresco

OKio是什么

Okio 补充了 java.io 和 java.nio 的内容,使得数据访问、存储和处理更加便捷。

Retrofit、OkHttp、OKio之间的关系

此处输入图片的描述

小实例 OkioUtil.java

  1. import android.os.Environment;
  2. import android.text.TextUtils;
  3. import android.util.Log;
  4. import java.io.Closeable;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import okio.BufferedSink;
  8. import okio.BufferedSource;
  9. import okio.Okio;
  10. import okio.Sink;
  11. import okio.Source;
  12. public class OkioUtil {
  13. private static final String FILE_NAME = Environment.getExternalStorageDirectory() + "/okio/dest.txt";
  14. private OkioUtil() {
  15. //Do Nothing
  16. }
  17. /**
  18. * 写入本地文件
  19. *
  20. * @param content
  21. * @return
  22. */
  23. public static boolean writeLocalFile(String content) {
  24. if (TextUtils.isEmpty(content))
  25. return false;
  26. Sink sink = null;
  27. BufferedSink bufferedSink = null;
  28. File file = new File(FILE_NAME);
  29. if (!file.exists()) {
  30. if (!file.mkdirs()) {
  31. Log.e(MainActivity.TAG, "new File(FILE_NAME) failed");
  32. return false;
  33. }
  34. }
  35. try {
  36. sink = Okio.sink(file);
  37. bufferedSink = Okio.buffer(sink);
  38. bufferedSink.writeUtf8(content);
  39. } catch (IOException e) {
  40. e.printStackTrace();
  41. return false;
  42. } finally {
  43. closeQuietly(bufferedSink);
  44. closeQuietly(sink);
  45. }
  46. return true;
  47. }
  48. /**
  49. * 读出本地文件
  50. *
  51. * @return
  52. */
  53. public static String readLocalFile() {
  54. Source source = null;
  55. BufferedSource bufferedSource = null;
  56. File file = new File(FILE_NAME);
  57. if (!file.exists()) {
  58. if (!file.mkdirs()) {
  59. Log.e(MainActivity.TAG, "new File(FILE_NAME) failed");
  60. return null;
  61. }
  62. }
  63. try {
  64. source = Okio.source(file);
  65. bufferedSource = Okio.buffer(source);
  66. return bufferedSource.readUtf8();
  67. } catch (IOException e) {
  68. e.printStackTrace();
  69. } finally {
  70. closeQuietly(bufferedSource);
  71. closeQuietly(source);
  72. }
  73. return null;
  74. }
  75. private static void closeQuietly(Closeable closeable) {
  76. if (closeable == null)
  77. return;
  78. try {
  79. closeable.close();
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. }

参考文章:
OkHttp GitHub Doc
Retrofit GitHub DocR Doc
Fresco GitHub Doc
Okio GitHub Video

更多请参考拆轮子系列:拆 Okio

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注