android io写入读取 txt 数据 封装
16lz
2021-01-25
为了方便大家 在项目中得到一些 写入和读出 数据
//生成写入的方法
private void writeData() { String filePath = "/sdcard/Syb/"; String fileName = "ImportantData.txt"; writeTxtToFile("Wx:lcti1314", filePath, fileName); } // 将字符串写入到文本文件中 private void writeTxtToFile(String strcontent, String filePath, String fileName) { //生成文件夹之后,再生成文件,不然会出错 makeFilePath(filePath, fileName); String strFilePath = filePath + fileName; // 每次写入时,都换行写 String strContent = strcontent + "\r\n"; try { File file = new File(strFilePath); if (!file.exists()) { Log.d("TestFile", "Create the file:" + strFilePath); file.getParentFile().mkdirs(); file.createNewFile(); } RandomAccessFile raf = new RandomAccessFile(file, "rwd"); raf.seek(file.length()); raf.write(strContent.getBytes()); raf.close(); } catch (Exception e) { Log.e("TestFile", "Error on write File:" + e); } }//生成文件 private File makeFilePath(String filePath, String fileName) { File file = null; makeRootDirectory(filePath); try { file = new File(filePath + fileName); if (!file.exists()) { file.createNewFile(); } } catch (Exception e) { e.printStackTrace(); } return file; }//生成文件夹 private static void makeRootDirectory(String filePath) { File file = null; try { file = new File(filePath); if (!file.exists()) { file.mkdir(); } } catch (Exception e) { Log.i("error:", e + ""); } }
//生成读取的方法
//读取指定目录下的所有TXT文件的文件内容private String getFileContent(File file) { String content = ""; if (!file.isDirectory()) { //检查此路径名的文件是否是一个目录(文件夹) if (file.getName().endsWith("txt")) {//文件格式为""文件 try { InputStream instream = new FileInputStream(file); if (instream != null) { InputStreamReader inputreader = new InputStreamReader(instream, "UTF-8"); BufferedReader buffreader = new BufferedReader(inputreader); String line = ""; //分行读取 while ((line = buffreader.readLine()) != null) { content += line + "\n"; } instream.close();//关闭输入流 } } catch (java.io.FileNotFoundException e) { Log.d("TestFile", "The File doesn't not exist."); } catch (IOException e) { Log.d("TestFile", e.getMessage()); } } } return content;}
// 最后直接调用上面封装好的方法
//写入writeData();
//读取
File file = new File("/sdcard/Syb/ImportantData.txt");String fileContent = getFileContent(file);Log.e("MainActivity", fileContent);
更多相关文章
- 一款常用的 Squid 日志分析工具
- GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
- RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
- Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
- eclipse导入android项目后出现错误的解决方法
- Eclipse中开发Android应用出现的error及solution汇总
- android 访问WebService
- Android(安卓)webview 一些奇怪的问题
- [转]Windows下用Git下载android源码