首先我们把java中的io流分为三类:字符流、字节流、转换流
字符流
以字符的形式对文件进行处理,我们写一段复制文件的代码,主要用到两个类FileReader(读文件到内存),FileWriter(将内存中的数据写到文件)
public class Main {
public static void main(String args[]) throws IOException{
//字符流
File file1 =new File("d:\\yll.txt");
File file2 = new File("d:\\copy.txt");
FileReader fr = new FileReader(file1);
FileWriter fw=new FileWriter(file2);
int len=-1;
char[] ch = new char[10];
while((len=fr.read(ch))!=-1){
fw.write(ch,0,len); ;
}
fr.close();
fw.close();
}
}
除此之外,字符流还提供了两个缓冲区,用于提高上面代码的速度,分别是BufferedReader和BufferedWriter,我们用这两个类来实现上面的功能。
public class Main {
public static void main(String args[]) throws IOException{
//字符流
File file1 =new File("d:\\yll.txt");
File file2 = new File("d:\\copy.txt");
FileReader fr = new FileReader(file1);
FileWriter fw=new FileWriter(file2);
int len=-1;
char[] ch = new char[10];
BufferedReader br = new BufferedReader(fr);
BufferedWriter bw = new BufferedWriter(fw);
while((len=br.read(ch))!=-1){
bw.write(ch,0,len);
}
br.close();
bw.close();
}
}
字节流
顾名思义,以字节的形式对文件进行读写,跟上面一样,一共提供了四个类:FileInputStream,FileOutputStream、BufferedInputStream、BufferedOutputStream。直接上代码吧
不用缓冲区实现:
public class Main {
public static void main(String args[]) throws IOException{
//字符流
File file1 =new File("d:\\yll.txt");
File file2 = new File("d:\\copy.txt");
//字节流
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
byte b[]=new byte[1024];
int len=-1;
while((len=fis.read(b))!=-1){
fos.write(b, 0, len);
}
fis.close();
fos.close();
}
}
用缓冲区实现:
public class Main {
public static void main(String args[]) throws IOException{
//字符流
File file1 =new File("d:\\yll.txt");
File file2 = new File("d:\\copy.txt");
//字节流
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
byte b[]=new byte[1024];
int len=-1;
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while((len=bis.read(b))!=-1){
bos.write(b, 0, len);
}
bis.close();
bos.close();
}
}
转换流
转换流一般在涉及编码的时候使用。
public class Main {
public static void main(String args[]) throws IOException{
//字符流
File file1 =new File("d:\\yll.txt");
File file2 = new File("d:\\copy.txt");
//转换流
InputStreamReader isr = new InputStreamReader(new FileInputStream(file1),"UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file2),"GBK");
char ch[] = new char[1024];
int len=-1;
while((len=isr.read(ch))!=-1){
osw.write(ch, 0, len);
}
isr.close();
osw.close();
}
}