java之IO节点流示例,其他情况举一反三都是类似的
Posted 小蜗牛爱远行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java之IO节点流示例,其他情况举一反三都是类似的相关的知识,希望对你有一定的参考价值。
-
I/O流的一般操作流程:
-
创建或者选择数据源
-
选择I/O流
-
创建操作对象
-
创建读取or存储的缓存区
-
具体操作,写入,读取,转换等等
-
示例:
/* *文件转字节流 */ public static byte[] fileToByteArray(String filePath){ //create source File file = new File(filePath); //select stream InputStream is = null; ByteArrayOutputStream os = null; try { //create object is = new FileInputStream(file); os = new ByteArrayOutputStream(); //create catch place byte[] flush = new byte[1024*10]; //do something int len = -1; while ((len=is.read(flush))!=-1){ String str = new String(flush, 0, len); os.write(str.getBytes()); } os.flush(); return os.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //先开后关 try { if (null != os){ is.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (null != is){ is.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; }
/* *字节流转文件 */ public static boolean byteArrayToFile(byte[] bytesArray, String filePath){ //create source File file = new File(filePath); //select stream ByteArrayInputStream is = null; FileOutputStream os = null; try { //create object is = new ByteArrayInputStream(bytesArray); os = new FileOutputStream(file); //create catch place byte[] flush = new byte[1024*10]; //do something int len = -1; while ((len=is.read(flush))!=-1){ os.write(flush, 0, len); } os.flush(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //先开后关 try { if (null != os){ is.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (null != is){ is.close(); } } catch (IOException e) { e.printStackTrace(); } } return false; }
public static boolean byteArrayToFile(byte[] bytesArray, String filePath){ //create source File file = new File(filePath); //select stream(高版本JDK,无需close,try会帮你执行close, 操作字节流使用BufferedI/O,大大提高性能) try (ByteArrayInputStream is = new ByteArrayInputStream(bytesArray); OutputStream os = new BufferedOutputStream(new FileOutputStream(file))){ //create catch place byte[] flush = new byte[1024*10]; int len = -1; while ((len=is.read(flush))!=-1){ os.write(flush, 0, len); } os.flush(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
-
以上是关于java之IO节点流示例,其他情况举一反三都是类似的的主要内容,如果未能解决你的问题,请参考以下文章