字符流是可以读取文字,而字节流不能(读文字的话会出现乱码)
字符流:是以Reader Writer结尾的
字节流:inputStream outputStream
public class bbbb {
public static void main(String[] args) {
File file=new File("D:/a/1.txt");
FileReader fr=null;
try {
fr=new FileReader(file);
int index=0;
while ((index= fr.read())!=-1){
System.out.println((char) index);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
写入
System.out.println("=========写入操作FileWriter===========");
File file=new File("D:/a/1.txt");
FileWriter fw=null;
try {
fw=new FileWriter(file,true);
String bb="不会";
fw.write(bb);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fw.close();//记得关流
} catch (IOException e) {
e.printStackTrace();
}
读写操作相当于把文件的内容复制到另一个新建文件中
System.out.println("===========读写操作============");
File file1=new File("D:/a/1.txt");
File file2=new File("D:/a/3.txt");
FileReader fr=null;
FileWriter fw=null;
try {
fr=new FileReader(file1);
fw=new FileWriter(file2);
char[]c=new char[(int)file1.length()];
int read=fr.read(c);
String res=new String(c,0,read);
System.out.println(res);
fw.write(res);
/*char[] c = new char[(int)file1.length()];
System.out.println("实际获得的数组的长度是:"+c.length);
int read = fr.read(c);
System.out.println("实际包含的字符数量为:"+read);
//为了处理多余字符 创建字符串时 进行处理
String res = new String(c,0,read);
System.out.println(res);
fw.write(res);*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}