承接Java-IO读写文件简单操作,这里再次写个小demo巩固一下知识点。
代码文件:demo.java
package com.test.demo; import java.io.*; public class demo { public static void main(String[] args) { // 写文件 writeFile(); // 读文件 readFile(); } /** * @function 读文件 * @param * @return void * @date 2018-10-06 14:08 */ public static void readFile() { // 1.通过File创建文件路径对象 File filePath = new File("src/com/test/demo/test.txt"); try { // 2.创建节点流 FileReader fr = new FileReader(filePath); // 3.创建处理流包装节点流 BufferedReader br = new BufferedReader(fr); // 4.创建存储数据空间 StringBuffer idList = new StringBuffer(); StringBuffer nameList = new StringBuffer(); StringBuffer descList = new StringBuffer(); // 5.读取数据 while(br.ready()){ // 字符串切割 String[] content = br.readLine().split("\t"); idList.append(content[0]); nameList.append(content[1]); descList.append(content[2]); } // 6.读取数据 System.out.println(idList); System.out.println(nameList); System.out.println(descList); // 7.关闭处理流、节点流等 br.close(); fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @function 写文件 * @param * @return void * @date 2018-10-06 13:14 */ public static void writeFile() { // 1.通过File创建文件路径对象 File filePath = new File("src/com/test/demo/test.txt"); try { // 2.创建节点流 FileWriter fw = new FileWriter(filePath); // 3.创建处理流包装节点流 BufferedWriter bw = new BufferedWriter(fw); // 4.构建数据 String[] idList = { "20181001", "20181002", "20181003", "20181004" }; String[] nameList = { "xiaoming", "xiaohong", "xiaofang", "xiaomei" }; String[] descList = { "小明", "小红", "小芳", "小美" }; // 5.写入数据 for(int i = 0; i < idList.length; i++){ // 以"Tab"键分隔字段 bw.write(idList[i] + "\t"); bw.write(nameList[i] + "\t"); bw.write(descList[i] + "\r\n"); } // 6.关闭处理流、节点流等 bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
运行截图:(产生文件:test.txt)
原文地址:https://www.cnblogs.com/xiaomingzaixian/p/9747349.html
时间: 2024-10-10 02:17:55