IO流
2023-07-24 16:53:16 4 举报
AI智能生成
java学习总结
作者其他创作
大纲/内容
<b><font face="思源黑体">字节流</font></b>
<b style=""><font face="思源黑体" color="#e74f4c"> 文件字节流<br>(FileInputStream)<br>(FileOutputStream)</font></b>
<b><font face="思源黑体"> 标准IO流操作流程:<br> 1.创建IO流对象<br> 2.读取IO流中的内容<br> 3.释放资源<br> FileInputStream fis=null; //初始化局部变量赋值初始值为null<br> try {<br> fis = new FileInputStream("文件相对/绝对路径"); //1.创建输入流对象<br> byte[] buf=new byte[1024]; //自定义缓冲区数组长度<br> int len;//定义长度变量<br> while((len = fis.read(buf)) != -1){ //将读取到的长度先赋值给len变量再判断是否为-1,为-1时结束循环<br> String str = new String(buf,0,len); //将该字节数组转换成字符串(字节数组,偏移量,有效长度)<br> System.out.println(str); //输出该文件包含字节<br> }catch (Exception e) { //捕获最大的异常<br> throw new RuntimeException(e);<br> }finally {<br> try {<br> if(fis != null){ //文件不为空<br> fis.close();} //释放资源<br> } catch (IOException e) {<br> throw new RuntimeException(e);}}</font></b><br>
<b><font face="思源黑体">一次读取缓冲区个字节,将读取到的内容放到字节数组中,<br> 并返回每次读取到的字节个数,如果读到流的末尾返回-1<br> * 可以指定数组的偏移量和读取的字节个数</font></b>
<b><font face="思源黑体" color="#e74f4c"> 字节缓冲流<br>BufferedInputStream<br>BufferedOutputStream</font></b>
<b><font face="思源黑体">只需要在字节流基础上包装一下</font></b>
<b><font face="思源黑体">FileInputStream fis=new FileInputStream(file1);<br>BufferedInputStream bis=new BufferedInputStream(fis);//包装成缓冲输入流<br>FileOutputStream fos=new FileOutputStream(file2);<br>BufferedOutputStream bos=new BufferedOutputStream(fos)//包装成缓冲输出流</font></b>
<b><font face="思源黑体" color="#e74f4c"> 对象字节流<br>ObjectOutputStream <br>ObjectInputStream</font></b><br>
<b><font face="思源黑体">字节缓冲流文件拷贝(</font></b>效率更高<b><font face="思源黑体">)</font></b>
<b><font face="思源黑体">字符流</font></b>
<b><font face="思源黑体" color="#e74f4c">文件字符流<br>FileReader<br>FileWriter</font></b>
<font color="#e74f4c" face="思源黑体"><b> 字符缓冲流<br>BufferedReader<br>BufferedWriter</b></font><br>
<b><font face="思源黑体">readline()方法一次读一行内容</font></b>
<b><font face="思源黑体"><br></font></b>
转换流<br>InputStreamReader<br>OutputStreamWriter
<font face="思源黑体" style="font-weight: bold;">IO流细节:(<font color="#e74f4c">特别注意使用IO流都需要序列化,在对象类中</font></font><font style="" color="#e74f4c"><b>实现Serializable接口</b></font><b><font face="思源黑体">)<br> 1.在使用输出流写出内容的时候,如果文件不存在则会自动创建,但要保证其父目录存在 <br> 2.在使用输出流时可以指定是否可追加的参数,如果设置为true,就会在原有的文件内容上追加<br> FileOutputStream fos=new FileOutputStream("相对/绝对路径",true);<br> 3.如果将IO流对象在try结构中创建,那么它会自动关闭流资源,不需要手动关闭,也不需要手动刷新缓冲区</font></b>
<font color="#e74f4c" face="思源黑体">推荐使用</font>
0 条评论
下一页