java文件流对象
package com.alibaba.caseutils.test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class INputAndOut { public static void main(String[] args) { String path="src\\test\\java\\read.txt"; InputStream inputStream = null; try { inputStream =new FileInputStream ( path ); for(;;){//for循环的死循环写法 int n =inputStream.read (); if(n==-1){//当满足特定的条件时退出 break; } System.out.println (n); } } catch (Exception e) { e.printStackTrace (); }finally { if(inputStream !=null){ try { inputStream.close (); } catch (IOException e) { e.printStackTrace (); } } } } }
229
191
151
==========================================================================
用FileInputStream
可以从文件获取输入流,这是InputStream
常用的一个实现类。此外,ByteArrayInputStream
可以在内存中模拟一个InputStream
:
范例:
package com.alibaba.caseutils.test; import java.io.*; public class INputAndOut { public static void main(String[] args) { byte[] bytes={11,22,127,44,-128,127}; try { InputStream inputStream = new ByteArrayInputStream ( bytes ); try { int n; for (; ; ) { n = inputStream.read (); if (n == -1) { break; } System.out.println ( n ); System.out.println ((char)n); } } finally { inputStream.close (); } } catch (IOException e) { e.printStackTrace (); } } }
package com.alibaba.caseutils.test; import java.io.*; public class INputAndOut { public static void main(String[] args) { byte[] bytes={11,22,127,44,-128,127}; InputStream inputStream = new ByteArrayInputStream (bytes); while (true){ try { int len = 0; while ((-1 != (len =inputStream.read () ))){ int n=inputStream.read (); System.out.println (n); } } catch (IOException e) { e.printStackTrace (); } } } }
上图是一个字节一个字节读取,而第二个图是安装字节数组读取,返回的是读取的数组个数 对应的方法
读取文件
package com.alibaba.caseutils.test; import java.io.*; public class JavaApidemo { public static void main(String[] args) { File file =new File ( "D:"+File.separator+"czq"+File.separator+"zq.txt" ); if(!file.getParentFile ().exists ()){ file.getParentFile ().mkdir (); } OutputStream outputStream = null; try { outputStream = new FileOutputStream ( file ,true); String str="Hello world\r\n"; outputStream.write ( str.getBytes () ); }catch (Exception e){ e.printStackTrace (); } } }
package com.alibaba.autotest_v2; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class Inputinter { public static void main(String[] args) throws Exception { String AA ="HELLO"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(AA.getBytes()); //将数据写入内存缓冲区 ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream();//创建从内存缓冲区读取流对象 int lenth; while ((lenth=byteArrayInputStream.read()) != -1) { byteArrayOutputStream.write(lenth); //保存数据 } byte[] bytes= byteArrayOutputStream.toByteArray(); System.out.println(new String(bytes)); } }
补充
内存流读取原理图
文件流读写终端
jiapengchu
posted on 2022-03-31 11:03 jiapengchu 阅读(148) 评论(0) 编辑 收藏 举报