package com.file; import java.io.*; /** * Created by DS on 2017/8/1. */ public class TestIO { public static void main(String[] args) { TestIO testIO = new TestIO(); // testIO.fileInputStreamTest(); // System.out.println();//换行 // testIO.fileReader(); // testIO.fileOutputStreamTest(); testIO.fileWriterTest(); } /** * 字节输入流 */ public void fileInputStreamTest() { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream("./chenyuzhu.txt"); byte[] bytes = new byte[1024];//可以想象一个水瓢,每次读1024个字节 int hasread = 0; //假如读1024大于0,就继续读 while ((hasread = fileInputStream.read(bytes)) > 0) { System.out.println(new String(bytes, 0, hasread)); } } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("发生异常了"); } catch (IOException e) { e.printStackTrace(); System.out.println("发生异常了"); } finally { if (fileInputStream != null) { try { //打开流 属于物理资源 GC也不能回收,最后导致内存泄漏 fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 字符输入流 */ public void fileReader() { FileReader fileReader = null; try { fileReader = new FileReader("./chenyuzhu.txt"); char[] chars = new char[32]; int hasread = 0; while ((hasread = fileReader.read(chars)) > 0) { System.out.println(new String(chars, 0, hasread)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 字节输出流 */ public void fileOutputStreamTest() { FileOutputStream fileOutputStream = null; try { // FileInputStream fileInputStream = new FileInputStream("./chenyuzhu.txt"); fileOutputStream = new FileOutputStream("./chenyuzhu1.txt"); // byte[] bytes = new byte[1024]; // int hasread = 0; // while ((hasread = fileInputStream.read(bytes)) > 0) { // //读一次我就写一次 // fileOutputStream.write(bytes, 0, hasread); // } //-------------------------------------------------------------------------- String s = "啦啦啦啦啦啦啦啦 我是庄周"; byte[] bytes1 = s.getBytes(); fileOutputStream.write(bytes1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 字符输出流 */ public void fileWriterTest() { FileWriter fileWriter = null; try { fileWriter = new FileWriter("./chenyuzhu2.txt",true); fileWriter.write("窗前明月光 疑是地上霜"); fileWriter.write("举头望明月 低头思故乡"); } catch (IOException e) { e.printStackTrace(); } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
IO流
最新推荐文章于 2024-08-23 15:44:17 发布