- package demo;
- import java.io.ByteArrayOutputStream;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.ArrayList;
- // 复制照片要求, 把照片用字节数组存到文件中, 再从文件中读数据写出来
- public class Test7 {
- // 把照片数据写入文件中
- public static void writePicture(byte[] b,String path) {
- OutputStream os=null;
- try {
- os=new FileOutputStream(path);
- os.write(b);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- try {
- if(os!=null) {
- os.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // 从指定文件中读取照片数据
- public static byte[] readPicture(String path) {
- FileInputStream fis=null;
- DataInputStream dis=null;
- try {
- fis=new FileInputStream(path);
- dis=new DataInputStream(fis);
- byte[] b=new byte[dis.available()];
- dis.read(b);
- return b;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- try {
- if(dis!=null) {
- dis.close();
- }
- if(fis!=null) {
- fis.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- // 从字节数组里读取内容写到指定文件中
- public static void writeByte(String path,byte[] b) {
- FileOutputStream fos=null;
- DataOutputStream dos=null;
- try {
- fos=new FileOutputStream(path);
- dos=new DataOutputStream(fos);
- dos.write(b); // 把数据写入二进制文件
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- try {
- if(dos!=null) {
- dos.close();
- }
- if(fos!=null) {
- fos.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // 用字节流读取照片数据到字节数组中
- public static byte[] getPictureByte(String Path) {
- FileInputStream fis=null;
- ByteArrayOutputStream baos=new ByteArrayOutputStream();
- try {
- fis=new FileInputStream(Path);
- byte[] b=new byte[1024];
- int len=-1;
- while((len=fis.read(b))!=-1) {
- baos.write(b, 0, len);
- }
- return baos.toByteArray();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }finally {
- try {
- if(fis!=null) {
- fis.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- public static void main(String[] args) {
- byte[] picture=getPictureByte("d:\\2.JPG");
- System.out.println(picture.length);
- writeByte("test.txt",picture);
- byte[] outImg = readPicture("test.txt");
- System.out.println(outImg.length);
- writePicture(outImg,"2.jpg");
- }
- }
来源: http://www.bubuko.com/infodetail-2905151.html