温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-04 12:38:09 来源:网络 阅读:369 作者:wx5d21d5e6e5ab1 栏目:编程语言

//读取图片到字节数组(内存),然后返回写入的字节数组
//读取返回的字节数组,写入到文件

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);  ///读取字节数组要用字节数组读取流,不能用FileInputStream文件读取流

        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();
        }
    }

}

}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI