IO流

    xiaoxiao2022-07-14  167

    先插入别人那里的一张图片 重要的就是read和write方法 以文件的复制为例 字节流

    package cn.itcast.Copy; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.management.RuntimeErrorException; /* * 将d:\\a.txt * 复制到d:\\b.txt */ public class Copy { public static void main(String[] args) { // 先创建两个流的对象 FileInputStream fis = null; FileOutputStream fos = null; //捕获异常 try{ fis = new FileInputStream("d:\\a.txt"); fos = new FileOutputStream("d:\\b.txt"); //字节输入流,读一个字节,输出流写一个字节 int len = 0; while((len = fis.read()) != -1){ fos.write(len); } }catch (IOException e) { System.out.println(e); throw new RuntimeException("运行失败"); }finally{ try { if(fis != null) fis.close(); } catch (Exception e2) { System.out.println(e2); throw new RuntimeException("关闭失败"); }finally{ try { if(fos != null ) fos.close(); } catch (Exception e3) { System.out.println(e3); throw new RuntimeException("关闭失败"); } } } } }

    字符流

    package cn.itcast.demo03; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.management.RuntimeErrorException; /* * 将d:\\a.txt * 复制到d:\\b.txt */ public class Copy { public static void main(String[] args) { // 老样子,首先建立两个流的变量 FileWriter fw = null; FileReader fr = null; // 捕获异常 try { // 绑定数据源 fr = new FileReader("d:\\a.txt"); fw = new FileWriter("d:\\b.txt"); int len = 0; char[] ch = new char[1024]; while ((len = fr.read(ch)) != -1) { fw.write(ch, 0, len); fw.flush(); } } catch (IOException e) { System.out.println(e); throw new RuntimeException("运行错误"); } finally { try { if (fr != null) fr.close(); } catch (Exception e2) { System.out.println(e2); throw new RuntimeException("关闭读入文件失败"); } finally { try { if (fw != null) fw.close(); } catch (Exception e2) { System.out.println(e2); throw new RuntimeException("关闭写入文件失败"); } } } } }

    注意:字符流的write()方法后必须刷新,即必须跟着写flush()方法

    缓冲流的构造方法中可以传递任意的字节输入输出流 BufferedWriter类特有的方法: void newLine() 写入一个行分隔符。

    Bufferedreader类特有的方法: String readLine() 读取一个文本行

    package cn.itcast.demo02; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; //利用字节输入输出缓冲流实现文件的复制 public class Copy { public static void main(String[] args) throws IOException { copyMethod(new File("d:\\buffered.txt"), new File("d:\\buffCopy.txt")); } private static void copyMethod(File src, File desc) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desc)); int len = 0; byte[] b = new byte[1024]; while ((len = bis.read(b)) != -1) { bos.write(b,0,len); } bis.close(); bos.close(); } }
    最新回复(0)