IO—文本文件的读和写(字符流)

    技术2025-01-10  13

    使用FileReader和FileWriter 路径问题参考印象笔记

    注意:最后流一定要关,不然会无法写入到文件

    读(读整个文本):

    @Test public void testRead() throws IOException { FileReader fileReader = null; try { File file = new File("a.txt"); fileReader = new FileReader(file); char[] arr = new char[5]; int len; while ((len=fileReader.read(arr))!=-1){ System.out.print(new String(arr,0,len)); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(fileReader!=null) fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } }

    写:

    @Test public void testWrite() throws IOException { FileWriter fileWriter = null; try { File file = new File("b.txt"); fileWriter = new FileWriter(file,true); fileWriter.write("hello"); fileWriter.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fileWriter!=null) fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }

    一边读一边写(复制):

    @Test public void ReadAndWrite() { FileReader fileReader = null; FileWriter fileWriter = null; try { File file = new File("a.txt"); File file2 = new File("b.txt"); fileReader = new FileReader(file); fileWriter = new FileWriter(file2); char[] arr = new char[5]; int len; while ((len=fileReader.read(arr))!=-1){ fileWriter.write(arr,0,len); fileWriter.flush(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(fileReader!=null) fileReader.close(); } catch (IOException e) { e.printStackTrace(); } try { if(fileWriter!=null) fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }

    为什么要在finally里关闭流? 答:如果流关闭写在try体里,当异常发生在流关闭前可能导致流无法关闭

    Processed: 0.008, SQL: 9