多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
1. try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, append))) 自动关闭文件流 ~~~ package net.aexit.galaxy.earth.common.utils; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by dailin on 2018/3/23. * 文件操作工具类 */ public class FilesUtil { /** * 将List数据写入文件 * @param values 数据 * @param path 文件目录 * @param append 是否追加 * @throws IOException */ public void writeToFile(List<String> values,String path,Boolean append) throws IOException { File file = new File(path); checkFile(file.getParent(),true); try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, append))) { for (String value : values) { bw.write(value); bw.newLine(); } bw.flush(); } } /** * 将文件转为List * @param path 文件路径 * @return 文件行列表 * @throws IOException */ public List<String> readFile(String path) throws IOException { List<String> values = new ArrayList<>(); FileReader fr = new FileReader(path); try (BufferedReader bufr = new BufferedReader(fr)) { String value; while ((value = bufr.readLine()) != null) { values.add(value); } } return values; } /** * 判断目录是否存在 * @param path 目录 * @param mkdir 是否创建目录 * @return * @throws IOException */ public Boolean checkFile(String path,Boolean mkdir) throws IOException { File paths = new File(path); if(!paths.exists()){ if (mkdir){paths.mkdirs();}; return false; } return true; } } ~~~ 最开始写入文件的时候没有判断目录是否存在,改正 ~~~ public class TestFile { public static void main(String[] args) { File file = new File("D:\\mmmmmmmmm\\sssss\\ppppppp\\texdddd.txt"); System.out.println(file.getParent()); \\获取上一级目录 System.out.println(file.getAbsoluteFile()); System.out.println(file.getAbsolutePath()); } } ~~~ ~~~ D:\mmmmmmmmm\sssss\ppppppp D:\mmmmmmmmm\sssss\ppppppp\texdddd.txt D:\mmmmmmmmm\sssss\ppppppp\texdddd.txt ~~~