第三次学JAVA再学不好就吃翔(part102)--拷贝图片

学习笔记,仅供参考,有错必纠


拷贝图片


逐个字节拷贝


  • 实现
package com.guiyang.bean;

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

public class Demo3_Copy {

	public static void main(String[] args) throws IOException {
		demo1();

	}

	private static void demo1() throws FileNotFoundException, IOException {
		FileInputStream fis = new FileInputStream("beiyesi.png");
		FileOutputStream fos = new FileOutputStream("copy.png");
		
		int b;
		
		while ((b = fis.read()) != -1) {
			fos.write(b);
		}
		
		fis.close();
		fos.close();
	}

}

全部字节一次拷贝


FileInputStream方法

  • available方法
public int available()

返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。简而言之,获取读的文件所有的字节个数。


  • read
public int read()

从此输入流中读取一个数据字节。简而言之,一次读取一个字节数组.

public int read(byte[] b)

从此输入流中将最多 b.length 个字节的数据读入一个byte数组中。

参数:b - 存储读取数据的缓冲区。
返回:读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。


FileOutputStream方法

  • write
public void write(int b)

将指定字节写入此文件输出流。


public void write(byte[] b)

将 b.length 个字节从指定 byte 数组写入此文件输出流中。


public void write(byte[] b, int off, int len)

将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。


实现

package com.guiyang.bean;

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

public class Demo3_Copy {

	public static void main(String[] args) throws IOException {
		Demo2();
	}

	private static void Demo2() throws FileNotFoundException, IOException {
		FileInputStream fis = new FileInputStream("beiyesi.png");
		FileOutputStream fos = new FileOutputStream("copy.png");
		
		byte[] arr = new byte[fis.available()];
		
		fis.read(arr);
		fos.write(arr);
		
		fis.close();
		fos.close();
	}

}

指定字节数拷贝


package com.guiyang.bean;

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

public class Demo4_ArrayCopy {

	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("beiyesi.png");
		FileOutputStream fos = new FileOutputStream("copy.png");
		byte[] arr = new byte[1024 * 2];
		int num;
		while ((num = fis.read(arr)) != -1) {
			System.out.println("有效字节个数为:" + num);
			fos.write(arr, 0, num);
			
		}
		
		fis.close();
		fos.close();
	}
}

输出:

有效字节个数为:2048
有效字节个数为:2048
有效字节个数为:582

猜你喜欢

转载自blog.csdn.net/m0_37422217/article/details/107480938