FileUtils.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.emato.ich.utils;
  2. import android.content.Context;
  3. import android.util.Log;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. /**
  9. * 默认会找/data/data/包名/file目录下的文件
  10. * MODE:
  11. * MODE_PRIVATE: 默认操作模式, 代表是有数据,写入会覆盖写入 0
  12. * MODE_APPEND: 会校验文件是否存在, 存在则追加写入, 不存在则创建 32768
  13. * MODE_WORLD_READABLE: 当前文件可以被其他应用读取 1
  14. * MODE_WORLD_WRITEABLE: 当前文件可以被其他应用写入 2
  15. */
  16. public class FileUtils {
  17. public static final String TAG = "FileUtils";
  18. private static final String path = "";
  19. public static void write(String fileName, String content, Context context, int mode){
  20. try (FileOutputStream outputStream = context.openFileOutput(fileName, mode)) {
  21. outputStream.write(content.getBytes());
  22. } catch (FileNotFoundException e) {
  23. Log.e(TAG, "write: 该路径下没有这个文件!", e);
  24. LoggingUtils.sendErrorLog("业务异常: 该路径下没有这个文件! ", e);
  25. } catch (IOException e) {
  26. Log.e(TAG, "write: 写入文件失败!", e);
  27. LoggingUtils.sendErrorLog("业务异常: 写入文件失败! ", e);
  28. }
  29. }
  30. public static String read(String fileName, Context context) {
  31. try (FileInputStream inputStream = context.openFileInput(fileName)) {
  32. byte[] bytes = new byte[1024];
  33. StringBuilder builder = new StringBuilder();
  34. int len = 0;
  35. while((len = inputStream.read(bytes)) > 0) {
  36. builder.append(new String(bytes, 0, len));
  37. }
  38. return builder.toString();
  39. } catch (FileNotFoundException e) {
  40. Log.e(TAG, "read: 读取的文件未找到! ", e);
  41. LoggingUtils.sendErrorLog("业务异常: 读取的文件未找到! ", e);
  42. } catch (IOException e) {
  43. Log.e(TAG, "read: 读取文件出现异常!", e);
  44. LoggingUtils.sendErrorLog("业务异常: 读取文件出现异常! ", e);
  45. }
  46. return "";
  47. }
  48. }