//1.从文本中读取并添加到集合,按行读取
1 public static void main(String[] args) throws IOException { 2 BufferedReader br = new BufferedReader(new FileReader("g.txt")); 3 ArrayList<String> arr = new ArrayList<>(); 4 5 String line; 6 while ((line = br.readLine()) != null) { // 按行读取文本文件 7 arr.add(line); // 添加至集合 8 } 9 10 for (int i = 0; i < arr.size(); i++) { 11 System.out.println(arr.get(i)); 12 } 13 } 14
//2.把集合中的数据写入到文本,每个数据一行
1 public static void main(String[] args) throws IOException { 2 ArrayList<String> arrStr = new ArrayList<>(); 3 4 arrStr.add("abc"); 5 arrStr.add("cde"); 6 arrStr.add("efg"); 7 arrStr.add("ghi"); 8 9 BufferedWriter bw = new BufferedWriter(new FileWriter("g.txt")); 10 11 for (int i = 0; i < arrStr.size(); i++) { 12 bw.write(arrStr.get(i)); 13 bw.newLine(); //每个数据一行 14 15 }// for 16 bw.close(); 17 } 18
//3.复制文本文件
// 法一:复制文本文件,使用缓冲字符流,一次读一个字符
1 BufferedReader br = new BufferedReader(new FileReader("c.txt")); 2 BufferedWriter bw = new BufferedWriter(new FileWriter("d.txt")); 3 4 int c; 5 while ((c = br.read()) != -1) { 6 bw.write(c); 7 //bw.flush(); 8 } 9 10 bw.close(); 11 br.close();
// 法二:复制文本文件,一次读一个数组
1 BufferedReader br = new BufferedReader(new FileReader("d.txt")); 2 BufferedWriter bw = new BufferedWriter(new FileWriter("e.txt")); 3 4 char[] ch = new char[1024]; 5 int len = ch.length; 6 while ((len = br.read(ch)) != -1) { 7 bw.write(ch, 0, len); 8 } 9 10 bw.close(); 11 br.close();
// 法三:复制文本文件,按行读取,只能用Buffered
1 BufferedReader br = new BufferedReader(new FileReader("e.txt")); 2 BufferedWriter bw = new BufferedWriter(new FileWriter("f.txt")); 3 4 String line; 5 while ((line = br.readLine()) != null) { 6 bw.write(line); 7 bw.newLine(); 8 } 9 10 bw.close(); 11 br.close(); 12
//法四:复制文本文件,一次写一个字符数组
1 public static void main(String[] args) throws IOException { 2 // 创建输入字符流 3 FileReader fr = new FileReader("b.txt"); 4 // 创建输出字符流 5 FileWriter fw = new FileWriter("c.txt"); 6 7 // 字符数组的方式写入 8 char[] ch = new char[1024]; 9 int len = ch.length; 10 while ((len = fr.read(ch)) != -1) { 11 fw.write(ch, 0, len); 12 fw.flush(); 13 } 14 15 fw.close(); 16 fr.close(); 17 } 18
//法五:复制文本文件,一次写一个字符
1 public static void main(String[] args) throws IOException { 2 // 创建字符流对象 3 FileReader fr = new FileReader("a.txt"); 4 5 FileWriter fw = new FileWriter("b.txt"); 6 7 int c; 8 while ((c = fr.read()) != -1) { 9 10 fw.write(c); 11 } 12 13 fw.close(); 14 fr.close(); 15 } 16
时间: 2024-10-21 14:43:31