zoukankan      html  css  js  c++  java
  • 通过java的i/o机制进行图片流的存储以及对网络图片的存储

    存储内地图片思路:首先把原有的图片以流的方式读取出来,再以流的方式存储到目标文件:

    package imgStream;
    
    import java.io.*;
    
    public class ImgStream {
        public static void main(String srga[]) {
            File source = new File("user.jpg");
            File desk = new File("G:\learn\javademoS\imgs");
            if (!desk.exists()) {
                desk.mkdir();
            }
            try {
                FileInputStream inputStream = new FileInputStream(source);
                FileOutputStream outputStream = new FileOutputStream(new File("G:\learn\javademoS\imgs\fang.jpg"));
                int ch = inputStream.read();
                while (ch != -1) {//当流结束时返回-1
                    outputStream.write(ch);
                    ch = inputStream.read();
                }
                inputStream.close();
                outputStream.close();
                System.out.println("写入流成功");
            } catch (FileNotFoundException e) {
                System.out.println("文件不存在:" + e.getMessage());
            } catch (IOException e) {
                System.out.println("文件读取错误:" + e.getMessage());
            }
        }
    }
    

     

    存储网络图片思路:构造一个url,然后请求网络数据,然后再以流的方式写到文件当中:

    package imgStream;
    
    import java.net.URL;
    import java.net.URLConnection;
    
    import java.io.*;
    
    public class ImgStreamS {
    
        private static void system() throws Exception {
            String path = "http://ui.51bi.com/opt/siteimg/images/fanbei0923/Mid_07.jpg";
            //构造URL
            URL url = new URL(path);
    
            //打开连接
            URLConnection con = url.openConnection();
            //请求时间
            con.setConnectTimeout(4*1000);
            //输入流
            InputStream is = con.getInputStream();
            //1K的数据缓冲
            byte[] bs=  new byte[1024];
            //数据长度
            int len;
            //输出的文件流
            File sf = new File("G:\learn\javademos\imgs");
            if(!sf.exists()){
                sf.mkdirs();
            }
            OutputStream os = new FileOutputStream(sf.getPath()+"\test.jpg");
            //开始读取
            while((len = is.read(bs)) != -1){
                os.write(bs,0,len);
            }
            //关闭所有连接
            os.close();
            is.close();
        }
    
        public static void main(String args[]) throws Exception {
            ImgStreamS imgStream = new ImgStreamS();
           
            system();
        }
    }
    

      

  • 相关阅读:
    ReflectionException: There is no getter for property named
    iframe发送post请求
    wget已安装但命令没找到
    linux性能观察命令
    ELK搭建
    python之中特性(attribute)与属性(property)有什么区别?
    Django中的日志详解
    创建fastdfs_nginx容器及nginx配置
    2. 顺序表 数据结构与算法(python)
    Ubuntu安装和卸载搜狗输入法
  • 原文地址:https://www.cnblogs.com/mmykdbc/p/8778286.html
Copyright © 2011-2022 走看看