Java必会编程题_字节流_图片的拷贝

字节流(InputStream,OutputStream)
除了文本文件,都使用字节流
read(byte[] b):从输入流中读取一定数量的字节并将其存储在缓冲区数组b中
返回:读入缓冲区的总字节数,如果由于流末尾已到达而不再有数据,则返回-1
write(byte[] b):将b.length个字节从指定的字节数组写入此输出流
write(byte[] b,int off,int len):将制定的字节数组中从偏移量off开始的len个字节写入此输出流

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

public class 字节流_图片的拷贝 {

	public static void main(String[] args)
	{
		//源文件
		File srcFile = new File("E:"+File.separator+"IO testFile"+File.separator+"任嘉伦1.jpg");
		//目标文件
		File targetFile = new File("E:"+File.separator+"IO testFile"+File.separator+"ccc"+File.separator+"任嘉伦1.jpg");
		copy( srcFile, targetFile);
	}
	public static void copy(File srcFile,File targetFile)
	{
		//确保目标文件路径存在
		File targetFolder = targetFile.getParentFile();
		if(!targetFolder.exists())
		{
			targetFolder.mkdirs();
		}
		//声明字节输入和输出流
		InputStream is = null;
		OutputStream os = null;
		try {
			//创建字节输入(读)和输出流(写)
			is = new FileInputStream(srcFile);
			os = new FileOutputStream(targetFile);
			
			//声明数组用于保存读出的字节
			byte[] arr = new byte[1024];//每次读1kb
			//定义变量记录读取到arr中的字节个数
			int length = -1;
			//开始拷贝
			while((length = is.read(arr)) != -1)
			{
				//将读到的length个字节写入到字节输出流中
				os.write(arr, 0, length);//将arr中从第0之后的length个字节写入到目标文件(读多少写多少)
				os.flush();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try {
				//关闭流
				if(is != null)
				{
					is.close();
				}
				if(os != null)
				{
					os.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}
}

发布了7 篇原创文章 · 获赞 0 · 访问量 81

猜你喜欢

转载自blog.csdn.net/qq_43717274/article/details/105571866