多Activity复用文本读写方法:是否需编写Helper类?
你的思路完全正确
把重复的文本读写逻辑抽成独立的Helper类是非常合理的实践,能直接解决代码重复问题,带来这些实际好处:
- 统一维护:后续要修改读写逻辑(比如换存储路径、优化IO操作),只需要改Helper类,不用逐个修改50个Activity
- 降低出错概率:避免复制代码时出现遗漏或错误,还能集中做异常处理的优化
- 代码更简洁:每个Activity只需要调用Helper的方法,不用冗余的实现代码
不过原代码直接抽成Helper类需要调整几个关键细节:
items变量的处理:原方法依赖Activity里的items成员变量,抽成Helper后要改成参数传入+返回值的形式:- 保存方法:把
items作为参数传进去,代替原来直接用成员变量的写法 - 加载方法:把解析后的
List<String>作为返回值返回,让调用的Activity自己接收赋值
- 保存方法:把
- IO操作的优化:原代码手动关闭流容易出现资源泄漏,建议用Java的
try-with-resources自动管理流资源 - 空值安全处理:原代码里
split[0].isEmpty()的判断有风险,如果文件为空或者解析后split数组为空,会触发数组越界,要先判断split的长度
调整后的Helper类示例大概是这样:
public class FileHelper { // 保存方法:接收Context、文件名、要保存的items列表 public static void saveTxtFile(Context context, String name, List<String> items) { File path = context.getApplicationContext().getFilesDir(); try (FileOutputStream writer = new FileOutputStream(new File(path, name))) { writer.write(items.toString().getBytes()); } catch (Exception e) { e.printStackTrace(); } } // 加载方法:返回解析后的List<String>,出错时返回空列表 public static List<String> loadContent(Context context, String name) { File path = context.getApplicationContext().getFilesDir(); File readFile = new File(path, name); if (!readFile.exists()) { return new ArrayList<>(); } byte[] content = new byte[(int) readFile.length()]; try (FileInputStream stream = new FileInputStream(readFile)) { stream.read(content); String s = new String(content); if (s.length() <= 2) { // 对应原代码substring(1, length-1),如果是"[]"格式,截取后为空 return new ArrayList<>(); } s = s.substring(1, s.length() - 1); String[] split = s.split(", "); if (split.length == 0 || split[0].isEmpty()) { return new ArrayList<>(); } return new ArrayList<>(Arrays.asList(split)); } catch (Exception e) { e.printStackTrace(); return new ArrayList<>(); } } }
每个Activity里调用就很简洁:
// 保存 FileHelper.saveTxtFile(this, "filename.txt", items); // 加载 items = FileHelper.loadContent(this, "filename.txt");
内容的提问来源于stack exchange,提问作者GymAndProgramming
相关产品推荐
相关产品推荐

