文件字符流只能写入和读取文本
读取字符文件
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class TestReader {
public static void main(String[] args) {
File src = new File("a.txt");
Reader reader = null;
try {
reader = new FileReader(src);
char[] flush = new char[1024];//读取1024个字符到缓存区里
int len = -1;
while ((len = reader.read(flush)) != -1) {
String str = new String(flush,0,len);
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
写入字符文件
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class TestWriter {
public static void main(String[] args) {
File src = new File("a.txt");
Writer writer = null;
try {
writer = new FileWriter(src,true);
//方法1
String msg = "这是添加的新的字符串\r\n";
writer.write(msg);
//方法2
writer.append("这是写入方法2").append("append方法\r\n");
//方法3
String str = "这是写入方法3";
char[] datas = str.toCharArray();//字符串转换成字符数组
writer.write(datas);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}