io流读取文件

时间:2022-11-01 07:21:58

package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;

public class test5 {

public static void main(String[] args) throws Exception {

String pathName = "C://123.txt";
File file = new File(pathName); //读取以上路径的文件

// InputStreamReader reader = new InputStreamReader(new
// FileInputStream(file));
//建立一个对象,吧文件内容转成计算机能读懂的语言
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = "";
line = br.readLine();
while (line != null) {

line = br.readLine();
System.out.println(line);
}

br.close();//流最后必须关闭

// 写入text文件

File file2 = new File("c://456.txt");
if(!file2.exists()){
file2.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(file2));
out.write("123\r\n");
out.write("456");
out.flush();//缓冲区压入文件
out.close();//最后记得关闭流

}
}