二进制文件(图片,视频等)的传输

DataInputStream DataOutputStream类

package Day18_Test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyPic {
	public static void main(String[] args) {
		FileInputStream fis = null;
		DataInputStream dis = null;
		
		FileOutputStream fos = null;
		DataOutputStream dos = null;
		try {
			fis = new FileInputStream("D:\\Desert.jpg");
			dis = new DataInputStream(fis);
			
			fos = new FileOutputStream("D:\\Desert2.jpg");
			dos = new DataOutputStream(fos);
			
			
			byte[] b = new byte[10240];
			int length = dis.read(b);
			while (length!=-1) {
				//此出保证了文件传输两端大小一致
				//文件没有读完时:length为每次数组的长度
				//文件读完时,length为当前读到数据的长度
				dos.write(b, 0, length);
				dos.flush();
				length = dis.read(b);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				if (dis!=null) {
					dis.close();
				}
				if (fis!= null) {
					fis.close();
				}
				if (dos!=null) {
					dos.close();
				}
				if (fos!=null) {
					fos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

你可能感兴趣的:(javase)