zoukankan      html  css  js  c++  java
  • java基础---IO流

    0.IO

      会使用File类操作文件或目录的属性

      熟练使用字节流读写文件

      熟练使用字符流读写文件

      会使用字节流读写二进制文件

     

    什么是流?

    流是指一连串流动的字符,是以先进先出方式发送信息的通

    1.File类常用方法

      

      File类:Java程序用于访问文件的属性

      

      boolean exists( ) 判断文件或目录是否存在

      boolean isFile( ) 判断是否是文件

      boolean isDirectory( ) 判断是否是目录

      String getPath( ) 返回此对象表示的文件的相对路径名

      String getAbsolutePath( ) 返回此对象表示的文件的绝对路径名

      String getName( ) 返回此对象表示的文件或目录的名称

      boolean delete( ) 删除此对象指定的文件或目录

      boolean createNewFile( ) 创建名称的空文件,不创建文件夹

      long length() 返回文件的长度,单位为字节, 如果文件不存在,则返回 OL

     

    举例:

                    //创建文件对象,创建File的实体

    File file=new File("c:\Java\hello.txt");

    if (file.exists()) {

    System.out.println("hello.txt文本存在");

    System.out.println("file是否是文件?true是,false不是--  "+file.isFile());

    System.out.println("file是否是文件夹? true是文件夹,false不是-- "+file.isDirectory());

    System.out.println("file对象的名字:"+file.getName());

    System.out.println("相对路径:"+file.getPath());

    System.out.println("绝对路径:"+file.getAbsolutePath());

    System.out.println("文件长度:"+file.length()+"字节");

     

    System.out.println("测试:getParent "+file.getParent());

    System.out.println("测试:getParentFile "+file.getParentFile());

    //删除文件

    /*if(file.delete()){

    System.out.println("文件删除成功");

    }else{

    System.out.println("文件删除失败");

    }*/

    }else{

    System.out.println("hello.txt文本不存在");

     

    //创建文件夹

    File file2=new File("c:\Java");

    if (!file2.exists()) {

    file2.mkdir();

    System.out.println("创建文件夹java成功");

    }

     

    //创建文件

    file.createNewFile();

    System.out.println("创建文本hello.txt成功");

    }

     

    }

     

     

    抽象类不能实例化

     

    2.java流分类

      按流向分:输出流(OutputStreamWriter)、输入流(InputStreamReader

      按处理数据单元分:字节流(字节输入流InputStream、字节输出流OutputStream)、字符流(字符输入流Reader、字符输出流Writer

     

     

    3.输入流/输出流

      1)输入流

      InputStreamReader是所有输入流的基类,它们都是抽象类,本身并不能创建实例来执行输入,但它们将是所有输入流的模板,所以它们的方法是所有输入流都可使用的方法。它们包含如下三个方法:

         int read()

     

         

         int read(byte[]/char[] b)

         int read(byte[]/char[] b, int off, int len)

      2)输出流

       OutputStreamWriter也非常相似,它们用来执行输出,两个流都提供了如下三个方法:

      void write(int c):将指定的字节/字符输出到输出流中,其中c既可以代表字节,也可以代表字符。

      void write(byte[]/char[] buf):将字节数组/字符数组中的数据输出到指定输出流中。

      void write(char[] cbuf, int off, int len):将字节数组/字符数组中从off位置开始,长度为len的字节/字符输出到输出流中。

     

    4.文件的读写

    文本文件的读写

     FileInputStreamFileOutputStream读写文本文件

     BufferedReaderBufferedWriter读写文本文件

    二进制文件的读写

     使用DataInputStreamDataOutputStream读写二进制文件

     

    5.文本文件的读写(字节流/字符流)

    字节流与字符流相比,字符流多了一个缓存流

       1)字节输入流InputStream/字节输出流OutputStream

        1InputStream类常用方法

             int read( )

             int read(byte[] b)

            ?int read(byte[] b,int off,int len)

             void close( )

            子类FileInputStream常用的构造方法

             FileInputStream(File file)

             FileInputStream(String name

        2OutputStream类常用方法

             void write(int c)

             void write(byte[] buf)

             void write(byte[] b,int off,int len)

             void close( )

         子类FileOutputStream常用的构造方法

            FileOutputStream (File file)

            FileOutputStream(Str

    举例:字节输入流 InputStream

            // 循环读取单个字节数据(使用文件循环读取流读取单个字节,实现多个打印)

    private static void method1(){

    try {

    //创建文件读取流对象

    FileInputStream fis=new FileInputStream("c:\java\hello.txt");

    int i=fis.read();//读取一个字节,返回读取的字节数据

    while (i!=-1) {

    System.out.println(i);

    i=fis.read();// 继续读取

    }

    fis.close();// 关闭资源

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch(IOException e){

    e.printStackTrace();

    }

    }

     

     

     

    // 使用文件读取流读取字节(数组形式读取)

    private static void method2() {

    try {

    // 创建文件读取流对象

    FileInputStream fis = new FileInputStream("c:\java\hello.txt");

    //放在数组中

    byte t[]=new byte[1024];

    int i = fis.read(t);// 最多读取t.length个长度的字节,返回读取的字节大小

    while (i != -1) {

    System.out.println("读取的长度:"+i);

    i = fis.read();// 继续读取

    }

    fis.close();// 关闭资源

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

     

    //数组形式的方法二

    private static  void method3() {

    try {

    // 创建文件读取流对象

    FileInputStream fis = new FileInputStream("c:\java\hello.txt");

    //放在数组中

    byte t[]=new byte[1024];

    int i=fis.read(t, 0, t.length);//2个参数表示从那个索引位置读取,第3个参数表示最多读取字节大小

    while (i != -1) {

    System.out.println("读取的长度:"+i);

    i = fis.read(t, 0, t.length);// 继续读取

    }

    fis.close();// 关闭资源

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

     

    }

    }

    举例:字节写入流

            //文件写入

    private static void method() {

    try {

    //文件写入流,第2个参数true表示在文件未尾追加内容,如果不写第2个参数或者写false表示覆盖原内容

    FileOutputStream fos = new FileOutputStream("c:\java\hello.txt",true);

    String str="网络安全";

        byte b[]=str.getBytes();

        fos.write(b, 0, b.length);

        System.out.println("写入成功");

        fos.close();

    } catch (FileNotFoundException e1) {

    e1.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

     

    举例:字节的读写

            //记事本文件的复制 读取hello.txt中的内容,复制到hh.txt

    private static void method2(){

    try {

    FileInputStream fis =new FileInputStream("c:\java\hello.txt");

    FileOutputStream fos=new FileOutputStream("c:\java\hh.txt");

    byte b[]=new byte[1024];

    int i=fis.read(b,0,b.length);

    while (i!=-1) {

    fos.write(b,0,i);

    i=fis.read(b,0,b.length);

    }

    fos.close();

    fis.close();

    } catch (FileNotFoundException e) {

     

    e.printStackTrace();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

     

    }

     

        2)字符输入流Reader、字符输出流Writer

           使用字符流读写文本更合适

    举例:字符输入流Reader

            // 创建字符流读取对象

    try {

    FileReader fr=new FileReader("c:\java\pet.txt");

    StringBuffer sb=new StringBuffer();

    char c[]=new char[1024];

    int len=fr.read(c);

    while (len!=-1) {

    sb.append(c); //把读取的字符串加到sb

    len=fr.read(c);

            }

    fr.close();

    System.out.println("读取的内容如下:"+sb.toString());

    //替换

    String nstr=sb.toString().replace("{name}", "ok").replace("{sex}", "").replace("{hobby}", "陶笛");

    System.out.println("替换后的内容"+nstr);

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

     

     

     

    举例:字符读取缓存流

          BufferedReader类(提高字符流读取文本文件的效率)

          BufferedReader类是Reader类的子类

          BufferedReader类带有缓冲区

          按行读取内容的readLine()方法

     

          // 创建字符流读取对象

    try {

    //创建字符流读取对象

    FileReader fr=new FileReader("c:\java\pet.txt");

    //字符读取缓存流

    BufferedReader br=new BufferedReader(fr);

    StringBuffer sb=new StringBuffer();

    String str=br.readLine();

    while (str!=null) {

    sb.append(str); //把读取的字符串加到sb

    str=br.readLine();

    }

    fr.close();

    System.out.println("读取的内容如下:"+sb.toString());

    //替换

    String nstr=sb.toString().replace("{name}", "ok").replace("{sex}", "").replace("{hobby}", "陶笛");

    System.out.println("替换后的内容"+nstr);

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

     

    }

     

     

     

    举例:字符输出流Writer

    //字符的写入

    private static void method() {

    try {

    Writer fw=new FileWriter("c:\java\hh.txt",true);

    BufferedWriter bw=new BufferedWriter(fw);

    String str="你好";

    bw.write(str);//写入

    bw.flush();

    bw.close();

    fw.close();

    System.out.println("写入成功");

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStacklurace();

    }

    }

     

     

    举例:字符流的读写

            //字符的读写

    private static void method2() {

    try {

    //读取流

    Reader in=new FileReader("c:\java\hh.txt");

    BufferedReader br=new BufferedReader(in);

    //写入流

    Writer out = new FileWriter("c:\java\tt.txt");

    BufferedWriter bw=new BufferedWriter(out);

    //按行读取

    String str=br.readLine();

    //循环读取/写入

    while (str!=null) {

    bw.write(str);

    str=br.readLine();

    }

    bw.flush();

    bw.close();

    out.close();

    br.close();

    in.close();

    System.out.println("文件复制成功");

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    6.二进制文件的读写

      DataInputStream

       FileInputStream的子类

       FileInputStream类结合使用读取二进制文件

      DataOutputStream

       FileOutputStream的子类

       FileOutputStream类结合使用写二进制文件

     

    举例:DataInputStream/DataOutputStream读写

                    //图片复制

    try {   //读取流

    FileInputStream fis=new FileInputStream("c:\java\left.png");

    DataInputStream dis=new DataInputStream(fis);

                            //写入流

    FileOutputStream fos=new FileOutputStream("c:\java\right.png");

    DataOutputStream dos=new DataOutputStream(fos);

    byte b[]=new byte[1024];

    int len=dis.read(b,0,b.length);

    while(len!=-1){

    dos.write(b);

    len=dis.read(b, 0, len);//再次读取,这里如果不赋初值将导致内存变大

    }

    dos.flush();

    dos.close();

    fos.close();

    dis.close();

    fis.close();

    System.out.println("图片复制成功");

    } catch (FileNotFoundException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

     

     

    7.对象流的读写

     

    举例:对象流的读写

    package demo;

    import java.io.Serializable;

    /**

     * 用户实体类,其中实现Serializable接口,目的是为完成对象流的读写

     * @author dell

     *

     */

    public class Users implements Serializable{

     

    private String uname;

    private String password;

     

     

    public Users() {

    super();

    }

    public Users(String uname, String password) {

    super();

    this.uname = uname;

    this.password = password;

    }

    public String getUname() {

    return uname;

    }

    public void setUname(String uname) {

    this.uname = uname;

    }

    public String getPassword() {

    return password;

    }

    public void setPassword(String password) {

    this.password = password;

    }

    }

     

     

    -------------------------------------------------------------------------

            //对象流的写入

    private static void objectWrite() {

    try {

    //文件写入流

    FileOutputStream out=new FileOutputStream("c:\java\ob1.txt");

    //对象写入流

    ObjectOutputStream oos=new ObjectOutputStream(out);

    //创建要写入的对象,该对象必须实现序列化接口

    Users user=new Users("admin", "132456");

    oos.writeObject(user);

    oos.flush();

    oos.close();

    out.close();

    System.out.println("写入完成");

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

     

    //对象流的读取,注意接收的对象类型

    public static void ObjectRead() {

    try {

    //文件输出/读取流

    FileInputStream in=new FileInputStream("c:\java\ob1.txt");

    //对象流的读取

    ObjectInputStream ois=new ObjectInputStream(in);

    //强制转换

    Users u=(Users)ois.readObject();

    System.out.println("读取的对象内容如下:"+"name:"+u.getUname()+",pwd:"+u.getPassword());

    ois.close();

    in.close();

    } catch (FileNotFoundException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    } catch (ClassNotFoundException e) {

    e.printStackTrace();

    }

    }

     

  • 相关阅读:
    cvsmooth平滑处理函数
    对图像频率的一些理解
    VIM 如何切换buffer
    Mplab X IDE 安装DMCI
    测试 使用橘子曰
    wlr设置 Blog Ping
    wlr快捷键
    使用Windows Live Writer写文章时不要用360清除垃圾
    如何将Windows live writer草稿转存到其他电脑上
    使用windows live writer写cnblog-1 安装wlr
  • 原文地址:https://www.cnblogs.com/-lyr/p/9668315.html
Copyright © 2011-2022 走看看