仅适用于处理字符文件:
读取字符文件:FileReader
//文件字符输入流:FileReader
public static void main(String[] args){
File src = new File("E:/个人文件夹/桌面/456.txt");
Reader reader = null;
try {
reader = new FileReader(src);
char[] flush = new char[1024];
int len;
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 (null != reader) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
写入字符文件:FileWriter
//文件字符输出流:FileWriter
public static void main(String[] args){
File src = new File("E:/个人文件夹/桌面/456副本.txt");
Writer writer = null;
try {
writer = new FileWriter(src);
String msg = "测试文件字符输出流";
char[] datas = msg.toCharArray();//字符串-->字符数组
writer.write(datas,0,datas.length);
writer.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != writer) {
writer.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
写入数据的部分也可以写成如下几种方式:
String msg = "测试文件字符输出流";
char[] datas = msg.toCharArray();//字符串-->字符数组
writer.write(datas,0,datas.length);
writer.flush();
String msg = "测试文件字符输出流";
writer.write(msg);
writer.flush();
writer.append("测试文件").append("输出流").append("\r\n end");
writer.flush();
拷贝字符文件:把reader和writer连接起来
//拷贝字符文件
public static void main(String[] args){
File src = new File("E:/个人文件夹/桌面/new.txt");
File desk = new File("E:/个人文件夹/桌面/new副本.txt");
Reader reader = null;
Writer writer = null;
try {
reader = new FileReader(src);
writer = new FileWriter(desk);
char[] flush = new char[1024];
int len;
while((len=reader.read(flush))!=-1) {
String msg = new String(flush,0,len);
writer.write(msg);
}
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != writer) {
writer.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (null != reader) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}