关于获取网络流,根据网络流转byte[],本地文件流转byte[],方法记录
生活随笔
收集整理的這篇文章主要介紹了
关于获取网络流,根据网络流转byte[],本地文件流转byte[],方法记录
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
/*** 根據(jù)文件路徑讀取byte[] 數(shù)組*/public static byte[] readFileByBytes(String filePath) throws IOException {File file = new File(filePath);if (!file.exists()) {throw new FileNotFoundException(filePath);} else {ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());BufferedInputStream in = null;try {in = new BufferedInputStream(new FileInputStream(file));short bufSize = 1024;byte[] buffer = new byte[bufSize];int len1;while (-1 != (len1 = in.read(buffer, 0, bufSize))) {bos.write(buffer, 0, len1);}byte[] var7 = bos.toByteArray();return var7;} finally {try {if (in != null) {in.close();}} catch (IOException var14) {var14.printStackTrace();}bos.close();}}}/*** 獲取網(wǎng)絡(luò)圖片流* * @param url* @return*/public static byte[] getImageStream(String url) {try {HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();connection.setReadTimeout(5000);connection.setConnectTimeout(5000);connection.setRequestMethod("GET");if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {InputStream inputStream = connection.getInputStream();return toByteArray(inputStream);}} catch (IOException e) {System.out.println("獲取網(wǎng)絡(luò)圖片出現(xiàn)異常,圖片路徑為:" + url);e.printStackTrace();}return null;}/*** InputStream轉(zhuǎn)化為byte[]數(shù)組* @param input* @return* @throws IOException*/public static byte[] toByteArray(InputStream input) throws IOException {ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buffer = new byte[4096];int n = 0;while (-1 != (n = input.read(buffer))) {output.write(buffer, 0, n);}return output.toByteArray();}
總結(jié)
以上是生活随笔為你收集整理的关于获取网络流,根据网络流转byte[],本地文件流转byte[],方法记录的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于selenium+java,实现部分
- 下一篇: java + selenium 种Web