FileReader的几个重载read方法的使用
一。不带参数的read()方法
public static void main(String[] args) {
File f=new File("hello.txt");
FileReader fi;
try {
fi=new FileReader(f);
int date;
/*不带参数的readf()方法,每次返回一个读取到的数据,数据类型是int,
本来数据是字符型的,但是返回的是int型,是因为每个字符对应一个ascii码
如果直接输出到控制台,会是字符对应的ascii码(一个数字),所以要强转下
变成字符输出
*/
while((date=fi.read())!=-1){
System.out.println((char)date);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
二。参数是char[]数组类型的参数
public static void main(String[] args) {
File f=new File("hello.txt");
FileReader fi= null;
try {
fi = new FileReader(f);
int len;
char[]ch=new char[5];
/*参数类型是字符数组,每次读取数组长度的数据,返回值len是返回的读取的
是读取的数据的长度,使用new 方法讲数组转换成一个字符串,(0,len)是将
数组的第0个到len个数据转化成字符串
*/
while((len=fi.read(ch))!=-1){
System.out.print(new String(ch,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(f!=null){
try {
fi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
错误的方式
/*
如果使用for循环每次打印数组长度的的数据,会存在一种问题,就是每次字符流读数
的时候,会将读到数据覆盖原来数组种每个数据,但是如果最后一次读的数据的数据
的长度不等于数组的长度,就没法完全覆盖这时候打印的话,就会将上次没有覆盖的
数据也打印出来
*/
while((len=fi.read(ch))!=-1){
for(int i=0;i<ch.length;i++){
System.out.print(ch[i]);
}
}
可以使用如下方式:
/*每次循环打印每次读取到数据长度的数据,或者使用第一种new String 的
方式,总的来说就是使用读取到的len,而不能使用数组长度,ch.lengtn()的
方式
while((len=fi.read(ch))!=-1){
for(int i=0;i<len;i++){
System.out.print(ch[i]);
}
}
将一个文件的内容复制到另一个文件种
public static void main(String[] args) {
File f = new File("hello.txt");
File f1 = new File("hello1.txt");
FileWriter fw = null;
FileReader fr = null;
try {
int len;
char[] ch = new char[5];
fw = new FileWriter(f1);
fr = new FileReader(f);
while ((len = fr.read(ch)) != -1) {
fw.write(ch,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null) {
fr.close();
if (fw != null)
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意
1.写文件也有会将未覆盖的内容写出的问题,所以使用fw.write(ch,0,len);方法,
2.如果要写入的文件不存在新建一个文件,如果存在直接覆盖,如果想要追加的得话,就要使用 fw = new FileWriter(f1,true);
字节流
字符流只能操作文本文件(比如txt,.class,.java,.php文件等)
操作非字符文件需要使用字节流(jpg,MP4,mp3,avi,doc,ppt等)
1)字符流处理非文本文件(例如图片),比如读取后写入到指定文件,会无法打开。
2)使用字节流处理文本文件有时候也会有异常,如果文本文件中只用英文和数字则不会 出现问题,如果含有中文就有可能出错,因为英文只是占一个字节,但是在UFT-8格式下,中文占三个字符,当我们每次read()或者write()的时候,就有可能将一个汉字给截开,造成乱码。(如果不sout输出到控制台,直接就读取以后写出没有问题)
1.字符处理文本文本文件,
2.字节处理非文本文件
3.字节可以处理文本文件(单独的读入,写出,不在内存层面做显示输出)
4.字符不能操作非文本文件。
public static void main(String[] args) {
File f=new File("hello.txt");
try {
FileInputStream fi=new FileInputStream(f);
byte[]bt=new byte[10];
int len;
while ((len=fi.read(bt))!=-1){
System.out.print(new String(bt,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}