写电子书系统的时候需要一个保存一些配置信息,
保存一下阅读进度 和 加入书架的书本。经过一些简单测试 打算就用这个了 ,具体配置文件的编写格式再行商议。
getFilesDir()、getCacheDir()(app私有储存文件目录,app被卸载时文件被删除,不用考虑6.0及以上权限限制)
readfile.java
package com.jinesc.readfile; import android.util.Log; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; public class ReadFile { //读取文件中的字符串 public static String readFile(String filePath) { File file = new File(filePath); StringBuilder stringBuilder = new StringBuilder(); char[] buf = new char[64]; int count = 0; try { FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(fileInputStream, "UTF-8"); while ((count = reader.read(buf)) != -1) { stringBuilder.append(buf, 0, count); } } catch (Exception e) { Log.e("读取文件出错", e.getMessage()); } return stringBuilder.toString(); } //将内容写入文件 public static void writeToFile(String filePath, String content) { File file = getFile(filePath); try { FileWriter fw = new FileWriter(file, false); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); fw.close(); } catch (Exception e) { Log.e("写文件出错", e.getMessage()); } } //根据路径获取文件 public static File getFile(String filePath) { File dir = new File(filePath); if (!dir.getParentFile().exists()) { dir.getParentFile().mkdirs(); } File file = new File(filePath); if (!file.exists()) { try { boolean flag = file.createNewFile(); if (!flag) { Log.e("创建文件失败", "createNewFile 失败"); } } catch (Exception e) { Log.e("创建文件失败", e.getMessage()); } } return file; } }
MainActivity.java
package com.jinesc.readfile; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.io.File; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv1 = (TextView) findViewById(R.id.txt2); tv1.setText("CHECK!!"); String file_path = getFilesDir().getPath() + File.separator + "self" + File.separator + "test.txt"; tv1.setText(getFilesDir().getPath()); ReadFile.writeToFile(file_path, "这里输入内容:杂牌军营www.jinesc.cn"); String kk = ReadFile.readFile(file_path); tv1.setText(kk); } }
发表评论