文件输入输出

package com.lovo.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class TestStream {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//文件的拷贝,这是可能在面试中出现的手工书写的代码!
//功能:将D:/test.avi 拷贝到 F:/wudi.avi
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//1、建立管道
fis = new FileInputStream("D:/test.avi");
fos = new FileOutputStream("F:/wudi.avi");

//2、操作管道
// int b = 0;//明明是读一个字节,为什么要用一个int来接?
// while((b = fis.read()) != -1){
// fos.write(b);
// }

byte[] b = new byte[1024];
int length = 0;//记录读取了多少个有效字节数
while((length = fis.read(b)) != -1){
fos.write(b,0,length);
fos.flush();//强制刷出缓冲区的内容
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//3、关闭管道
if(fis != null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated block
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

原文地址:https://www.cnblogs.com/fengshaolingyun/p/6785147.html