最近学了IO的一些内容,想把每一种流都弄清楚,就FileInputStream和FileOutputStream为例。编写了5种复制文件的方法。要是我有新的想法我会再补充的。
方法一:
File file = new File("D:\\demo.txt");
try {
FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
FileInputStream in = new FileInputStream(file);
int len = (int) file.length();//得到文件的长度
int hasRead = 0;
int temp = 0;
while((hasRead=in.read())!=-1){
out.write(hasRead);
temp++;
if(temp==len){//当读取的长度和文件长度相同时停止
break;
}
}
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
方法二:
File file = new File("D:\\demo.txt");
try {
FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
FileInputStream in = new FileInputStream(file);
int len = (int) file.length();//得到文件的长度
byte[] b = new byte[len];
in.read(b, 0, len);
out.write(b);
/*
* out.flush(); 最好有该方法。
* flush all the streams immediately before close them,
* otherwise data left in the buffer when the stream is closed may get lost
*/
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
方法三:
File file = new File("D:\\demo.txt");
try {
FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
FileInputStream in = new FileInputStream(file);
int len = (int) file.length();//得到文件的长度
byte[] b = new byte[len];
for(int i=0; i<b.length; i++){
b[i] = (byte)in.read();
}
out.write(b);
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
方法四:
File file = new File("D:\\demo.txt");
try {
FileOutputStream out = new FileOutputStream("D:"+File.separator+"me.txt");
FileInputStream in = new FileInputStream(file);
int len = (int) file.length();//得到文件的长度
byte[] b = new byte[len];
do{
in.read(b, 0, len);
out.write(b);
}while(in.available()>0);
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
方法五:
File f=new File("D:\\demo.txt");
try {
FileInputStream input=new FileInputStream(f);
FileOutputStream output = new FileOutputStream(new File("D:\\me.txt"));
byte b[]=new byte[input.available()];
input.read(b, 0,input.available() ); //available() 返回可以无阻塞地读取的字节数
output.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}