java _io_图片到内存(字节数组),字节数组到文件,练习文件流和字节数组流

//图片读取到字节数组中,字节数组写出到文件

public class test{
    public static void main(String[]args)
    {
        String path="C:/Users/10853/eclipse-workspace/hell/linux学习路线.png";

    byte[] data=toByteArray(path); //图片不能直接到字节数组中,is.read()返回的是int类型的大小,new String是解码
    //需要写入字节数组(内存)再通过方法返回到字节数组里
    //图片不能直接转换成字符串
    toFile(data,"D:/d/to.txt");

}
//图片到字节数组中
public static byte[] toByteArray(String path)
{
    File f =new File(path);
    byte[] last=null;

    InputStream is =null;  //选用字节流是因为,字符流只能读纯字符文本
    ByteArrayOutputStream bos=null;

    try {
        is =new FileInputStream(f);
        bos =new ByteArrayOutputStream();

        byte[] flush=new byte[1024*10];
        int len=-1;
        try {
            while((len=is.read(flush))!=-1)
            {
                bos.write(flush,0,len);  //写出到字节数组中
                bos.flush();
            }

            return bos.toByteArray();  //不返回字节数组的话,不知道读取哪段内存

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }finally
    {
        try {
        if(null!=is)
        {
            is.close();
        }

        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    return null;

}

//字节数组写出到文件
//字节数组读取到程序中 ByteArrayInputStream
//程序写出到文件 FileOutputStream

public static void toFile(byte[] src,String path)
{
    InputStream is=null;
    OutputStream os=null;
    try
    {
        is=new ByteArrayInputStream(src);
        os=new FileOutputStream(path);
        byte[] flush =new byte[1024*10];
        int len=-1;
        while((len=is.read(flush))!=-1)
        {
            os.write(flush,0,len);
            os.flush();
        }

    }catch(IOException e)
    {
        e.printStackTrace();
    }finally {
        try {
            if(null!=os)
            {
                os.close();
            }
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }

}

}

猜你喜欢

转载自blog.51cto.com/14437184/2423272