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