这里向文本(.text)文件中输入数据和读取文本中的数据
写入:FileWriter
package c20190430;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) {
String path = "E:\\新建文件夹\\test.txt";
File file = new File(path);
//输出流
FileWriter fw=null;
//缓冲流
BufferedWriter bw=null;
try {
// 构造方法的true 表示不覆盖内容 默认是false 会覆盖原来的内容
fw= new FileWriter(file,true);
bw=new BufferedWriter(fw);
//创建新行
bw.newLine();
bw.write("缓冲流00");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
//冲刷
bw.flush();
//关闭通道
bw.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
写入文本数据如下
读取:FileReader
package c20190430;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class TestFileReader {
public static void main(String[] args) {
String path = "E:\\新建文件夹\\test.txt";
File file = new File(path);
FileReader fr = null;
//缓冲流 Buffered
//缓冲字符流
BufferedReader br = null;
try {
//创建字符流对象
fr =new FileReader(file);
//将字符串转换成缓冲流对象
br = new BufferedReader(fr);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//读取一行
String str = br.readLine();
while(str!=null) {
System.out.println(str);
str = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
读出文本内容如下