文件写入:
// 写入数据保存在本地D:/user/error/目录下 private void write() { //获取系统毫秒数 long currentTimeMillis = System.currentTimeMillis(); String ts = String.valueOf(currentTimeMillis); // 文件名称系统毫秒数 String filepath = "D:/user/error/" + String.valueOf(currentTimeMillis) + ".txt"; File file = new File(filepath); //判断文件是否存在,不存在则创建 if (!file.exists()) { file.getParentFile().mkdirs(); } OutputStreamWriter opw; try { opw = new OutputStreamWriter(new FileOutputStream(filepath), "GBK"); BufferedWriter bufw = new BufferedWriter(opw); bufw.write("写入数据123456"); bufw.close(); opw.close(); } catch (Exception e) { e.printStackTrace(); } }
文件读取:
public void read() { String filepath = "D:/user/error/"; File file = new File(filepath); //获取D:/user/error/目录下所有文件 File[] files = file.listFiles(); Arrays.sort(files); String read = ""; try { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { InputStreamReader opw = new InputStreamReader(new FileInputStream(files[i]), "GBK"); BufferedReader bufr = new BufferedReader(opw); read = bufr.readLine(); bufr.close(); System.out.println(read); //删除当前文件 files[i].delete(); } } } catch (Exception e) { e.printStackTrace(); } }