java io 下载文件 字节流io典型应用
public String downLoadFromUrl(String urlStr) { try { String fileName = getRandomString(20)+".jpg"; String savePath = "/data/back"; // fileName = urlStr.substring(urlStr.lastIndexOf("/")+1); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(3*1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if(!saveDir.exists()){ saveDir.mkdir(); } File file = new File(saveDir+File.separator+fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if(fos!=null){ fos.close(); } if(inputStream!=null){ inputStream.close(); } System.out.println("info:"+url+" download success"); String localFile = saveDir+File.separator+fileName; File fileLocal = new File(localFile); String retUrl = upload(fileLocal); fileLocal.delete(); return retUrl; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); }
//得到输入流 InputStream inputStream = conn.getInputStream();
得到返回字节流
public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); }
读取InputStream,将字节流灌入byte数组,通过ByteArrayOutputStream向Byte数组写入数据,这里的ByteArrayOutputStream无非是起一个合并每次读取byte[]的嫁接功能,也可以不用,自己拼接,只要将InputStream全部压入byte[]即可
File file = new File(saveDir+File.separator+fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData);
通过FileOutputSteam在本地文件中写入数据
核心:
InputStream-byte[]-OutputStream(FileOutputStream)
byte[]为中介
参考:http://blog.csdn.net/qq_25184739/article/details/51205186
2.输出字节流OutputStream
IO 中输出字节流的继承图可见上图,可以看出:
1. OutputStream是所有的输出字节流的父类,它是一个抽象类。
2. ByteArrayOutputStream、FileOutputStream是两种基本的介质流,它们分别向Byte数组、和本地文件中写入数据。PipedOutputStream是向与其它线程共用的管道中写入数据。
3. ObjectOutputStream和所有FilterOutputStream的子类都是装饰流。