二进制文件的读写

 

    1.java.io.File    //所导入的包,表示文件或文件夹

  2.File f = new File("文件路径");

  3.注意:相对路径:非web项目的相对都是以项目为起点。(src/a/txt(建议)
          绝对路径:f:/bin/a.txt(以盘符开头)

  4.文件常见方法
    boolean flag = f.exists(); //文件是否存在
    flag = f.isFile(); //是否是文件
    flag = f.isDirextory(); //是否是目录
    str = f.getPath(); //获得文件的相对路径
    str = f.getAbsolutePath(); //获取文件的绝对路径
        str = f.getName(); //获取文件的目录或名称
    flag = f.delete(); //删除文件或目录
    flag = f.createNewFile(); //创建文件
    long = f.length(); // 返回文件长度
      注:注意flag不能操作文件内容

    3,Inptstream/OutputStream
    文件:FileInptstream/FileOutputStream
      3.1 Inptstream(输入流)
        数据从文件到java代码中,
        int read(); //读取一个字节
        int read(byte[]); //读取一串字节
        long avaliable; //文件长度

      3.2 FileInptstream(字节文件输入流)
        new FileInptstream(File)
        new FileInptstream("文件路径+文件名")

      3.3 OutputStream(输出流)
        数据从java代码中,写到文件或其他介质中。
        void write (字节);//写入一个字节
        void write(byte[]); //写入字节数组

      3.4 FileOutputStream
        new FileOutputStream(file)
        new FileOutputStream("文件路径+文件名")
        new FileOutputStream("文件路径+文件名",boolean)

          注意:a.boolean:表示是否向文件末尾追加,如果是true,表示
                追加,false表示不追加(也就是覆盖),默认值为false

             b.创建FileOutputStream实咧时,
                如果相应的文件并不存在,则会自动创建一个空的文件。

    4.Reader/writer(字符流)
        //能够用文本编辑器打开的文件,不乱码就是字符文件
        //用文本编辑器打开乱码的,就是字节文件

      4.1 FileReader
        int b = fr.read();//读一个字符
        int length = fr.read(char[]);//读取字符数组
      4.2 FileWriter
        fw.write(char);//写一个字符
        fw.write(char[]);//写字符数组

      4.3 BufferedReader(字符输入缓冲流)
        BufferedReader br = new BufferedReader
                  (new FileReader("文件路径"));
        String str = br.readLine();//读取一行字符
      4.4 BufferedWriter bw =
        new BufferedWriter(new FileWriter("文件路径"));
 小结:
   1.读写字符文件
      BufferedReader br = new BufferedReader(new FileReader(文件));
      BufferedWriter bw = new BufferedWriter (new FileWriter(文件));
    2.读写字节文件
      DataInputStream dis = new DataInputStream(new FileInputStream(文件));
      DataOutputStream dos = new DataOutputStream( new FileOutputStream(文件));
   3.读取整个字符文件
        String str = null;
      while((str = br.readLine())!=null){
          System.out.println(str)
      }

   4.读取整个字节文件
    int b;
    while((b=dis.read())!=-1){
        System.out.println(b);
      }
      

 

posted @ 2017-05-10 19:16  此昵称仅此一个  阅读(500)  评论(0编辑  收藏  举报