public class CharStream { public static void main(String[] args) { CharStream charStream = new CharStream(); //1、字符输入流,表示把文件写入到硬盘中 charStream.outPutStream("D:\\2.txt"); //2、字符输出流,表示想硬盘读出文件显示出来 charStream.inputStream("D:\\2.txt"); } private void inputStream(String path) { File file = new File(path); if (!file.exists()) { IAssert.throwMsg("文件不存在:" + path); } //todo 下面两行都可以实现字节流读取 FileReader fileReader = null; try { fileReader = new FileReader(file); } catch (FileNotFoundException e) { IAssert.throwMsg("文件不存在:" + path); } try { char[] chars = new char[1024]; int len = fileReader.read(chars); while (len != -1) { len = fileReader.read(chars); } String currentData = new String(chars); System.out.println("读出的数据为:" + currentData); //必须手动关闭,因为fileInputStream不属于内存的资源,导致垃圾回收器无法回收这些不用的资源。 fileReader.close(); } catch (IOException e) { IAssert.throwMsg("写入失败"); } } private void outPutStream(String path) { File file = new File(path); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { System.out.println("创建文件失败:" + path); } } String content = "我是中国人123"; FileWriter fileWriter = null; try { fileWriter = new FileWriter(file); } catch (FileNotFoundException e) { IAssert.throwMsg("未找到文件:"+path); } catch (IOException e) { e.printStackTrace(); } try { fileWriter.write(content); fileWriter.close(); } catch (IOException e) { IAssert.throwMsg("写入失败"); } } }
字符流FileReader与FileWriter
最新推荐文章于 2022-06-22 23:10:12 发布