Java流--简单讲解

File类

  • java.io.File类代表硬盘上的一个文件或者文件夹,提供了大量的文件操作:删除文件、修改文件、得到文件修改日期、建立目录。列表文件等等。
  • java中文件路径的表示方式:
    • Windows中表示:C:\a.txt
    • java中表示:
      • c:\a.txt
      • c:/a.txt
  • File类的构造方法
    • 构造方法 :File类没有无参构造方法
    • File(String pathname)
    • File(String pathname,String child)
    • File(File parent,String child)
  • File类的常用方法
    • createNewFile():boolean
    • mkdir()/mkdirs():boolean
    • delete():boolean
    • deleteOnExit():boolean
    • exists():boolean
    • isFile():boolean
    • isDirectory():boolean
  • File类的常见方法

    • getPath():String 创建时使用的是相对路径则返回相对路径,反之亦然
    • getName():String
    • getParent():String
    • getAbsolutePath():String 返回决定路径
    • list():String[] 返回目录当前file对象代表的目录下所有文件、文件夹名

      public class TestFile1{
      public static void main(String args[]) throws exception{
          File f0 = new File("abc.txt");
          f0.createNewFile();
      
          File f1 = new File("abc/abc");
          f1.mkdirs();
      
          File f2 = new File("cde","bcd/java.txt");
          System.out.println(f2.getPath());
          System.out.println(f2.getParent());
          System.out.println(f2.getName());
          System.out.println(f2.getAbsolutePath());
      
          File f5 = new File("c:");
          System.out.println(f5.isDirctory());//true
      
  • 递归的读取文件

    import java.io.*;
    public class Test {
        public static void main (String [] args) {
            listFile(new File("E:\\资料\\html+css\\");
         }
        //递归读取某个目录及目录下的所有文件
        private static void listFile(File f) {
            File[] files = f.listFileS();
            for (File file : files  ) {
                System.out.println(file.getName()+"\t\t"+(file.isFile()?"文件":"目录")+"\t\t"+file.getParent()+"\t\t"+file.getAbsolutePath());
                if(file.isDirctory()) {
                    listFile(file);
                }
            }
        }
    }
    

IO

  • I/O概念
    • I/O(input/output),即输入/输出端口。每个设备都会有一个专用的I/O地址,用来处理自己的输入输出信息。CPU与外部设备、存储器的连接和数据交换都需要通过接口设备来实现,前者被称为I/O接口,而后者则被称为存储器接口。存储器通常在CPU的同步控制下工作,接口电路比较简单;而I/O设备品种繁多,其相应的接口电路也各不相同,因此,习惯上说到接口只是指I/O接口。
  • 流的概念
    • “流”是一个抽象的概念,它是对输入输出设备的一种抽象理解,在java中,对数据的输入输出操作都是以“流”的方式进行的。“流”具有方向性,输入流、输出流是相对的。当程序需要从数据源中读入数据的时候就会开启一个输入流,相反,写出数据到某个数据源目的地的时候也会开启一个输出流。数据源可以是文件、内存或者网络等。
  • I/O流的分类
    • 输入流、输出流
    • 字节流、字符流
    • 节点流、过滤流

字节输入流

  • 字节流的概念
    • 传输的数据单位是字节,也意味着字节流能够处理任何一种文件
  • InputStream是字节输入流,InputStream是一个抽象类,所有实现了inputStream的类都是字节输入流,主要了解一下子类即可
    这里写图片描述

文件字节输入流(FileInputStream)

  • FileInputStream 主要按照字节方式读取文件
  • FileInputStream 常用方法
    • FileInputStream(String filename);
    • FileInputStream(File file);
    • int read(); 注意这里返回值的类型是int,指读取的内容
    • int read(byte[] buf); 读取内容填充到buf中,返回读取的长度
    • close();

文件字节输入流(FileInputStream)示例

在text.txt文件中,写入字符ABC。注意text.txt文件的路径

    public class TestInputStream1 {
        public static void main(String args[]) throws Exception {
            InputStream is = new FileInputStream("text.txt");
            System.out.println(is.read());// 65
            System.out.println(is.read());// 66
            System.out.println(is.read());// 67
            System.out.println(is.read());// -1
            is.close();
        }
    }

    public class TestInputStream2 {
        public static void main(String args[]) throws Exception {
        InputStream is = new FileInputStream("text.txt");
        int len = 0;
        while ((len = is.read()) != -1) {
            char c = (char) len;
            System.out.println(c);
        }
    }
}
/**
 *A
 *B
 *C
 **/

- int read(byte[] bs)

        public class TestInputStream {
            public static void main(String args[]) throws Exception {
                InputStream fin = new FileInputStream("oracle.txt");
                byte[] bs = new byte[6];
                int len = 0;
                while ((len = fin.read(bs)) != -1) {
                    for (int i = 0; i < len; i++) {
                        System.out.print((char) bs[i]);
                    }
                    System.out.println();
                }
                fin.close();
        }
    }
    /**
     *ABC
     **/

- int read(byte[] b, int off, int len);
- 从输入流中读取(最大)len个字节,填充到数组b中,从b的off索引处开始填充。

字节输出流(OutputStream)

  • 所有实现了OutputStream都是字节输出流
    这里写图片描述

文件字节输出流(FileOutputStream)

  • FileOutputStream的常用方法
    • FileOutputStream(String path);
    • FileOutputStream(File file);
    • close();
    • void write(int v);
    • void write(byte[] bs);
    • void write(byte[] bs,int off,int len);

文件字节输出流(FileOutputStream)示例

    public class TestOutputStream {
        public static void main(String args[]) throws Exception {
            String hello = "Hello World";
            byte[] bs = hello.getBytes();
            FileOutputStream fout = new FileOutputStream("test.txt");
            fout.write(bs);
            fout.close();
        }
    }

- 向文件中追加内容的方式
- FileOutputStream(String path,boolean append);
- FileOutputStream(File file,boolean append);

             public class TestOutputStream {
                public static void main(String args[]) throws Exception {
                    String hello = "Hello World";
                    byte[] bs = hello.getBytes();

                    FileOutputStream fout = new FileOutputStream("test.txt", true);
                    fout.write(bs);
                    fout.close();
                }
            }

字节缓冲流(过滤流)

  • BufferedStream

    • BufferedInputStream
    • BufferedOutputStream

      public class TestBufferedStream {
          public static void main(String args[]) throws Exception {
              String data = "Hello World";
              byte[] bs = data.getBytes();
              // 创建节点流
              FileOutputStream fout = new FileOutputStream("test.txt");
              // 封装过滤流
              BufferedOutputStream bout = new BufferedOutputStream(fout);
              // 写数据
              bout.write(bs);
              // 关闭外层流
              bout.close(); // bout.flush();
          }
      }
      

字符编码

  • 常见的编码规范(字符集)
    • ASCII:长度是一个字节,共8位,最多可以表示256个字符
    • ISO-8859-1: 通常叫做Latin-1,属于单字节编码,最多能表示的字符范围是0~255,应用于英文系列
    • GB2312/GBK: 汉字的国标码,专门用来表示汉字,是双字节编码,而英文字母和iso8859-1一致(兼容iso8859-1编码)。其中gbk编码能够用来同时表示繁体字和简体字,而gb2312只能表示简体字,gbk是兼容gb2312编码的
    • UTF-8: 1到6个字节变长编码,可以用来表示/编码所有字符
  • 编码: 将字符转换为字节;解码: 可以用来表示/编码所有字符
  • 乱码问题

    • 编码时采用一种字符集,但是解码时使用了其他的字符集

      String oname = "测试";
      byte[] bs = oname.getBytes("GBK");
      String dname = new String(bs, "GBK");
      System.out.println(dname); // 测试
      
      String oname = "测试";
      byte[] bs = oname.getBytes("GBK");
      String dname = new String(bs, "UTF-8");
      System.out.println(dname);// ????
      

字符输入流

  • 所有实现了Reader都是字符输入流
    这里写图片描述

    字符输出流

  • 所有实现了Writer都是字符输出流
    这里写图片描述

字符流

不推荐使用,无法指定字符编码

  • FileReader
    • FileReader(String fileName);
    • close();
    • int read(char[] cbuf);
  • FilerWriter
    • FileWriter(String fileName);
    • close();
    • write(String value);

转换流

  • InputStreamReader和OutputStreamWriter

    • 特点
      • 可以把一个字节流转换成一个字符流
      • 在转换时可以执行编码方式
    • InputStreamReader
      • InputStreamReader(InputStream is);
      • InputStreamReader(InputStream is,String charSet);
      • int read(char[] cbuf);
    • OutputStreamWriter

      • OutputStreamWriter(OutputStream is);
      • OutputStreamWriter(OutputStream is,String charSet);
      • write(char[] cbuf,int off,int len) 写入字符数组的某一部分
      • write(int c); 写入单个字符
      • write(String str,int off,int len); 写入字符串的某一部分

        public class TestInputStreamReader {
            public static void main(String args[]) throws Exception {
                InputStream is = new FileInputStream("oracle.txt");
                InputStreamReader ir = new InputStreamReader(is);
                char[] value = new char[1024];
                int len = 0;
                while ((len = ir.read(value)) != -1) {
                    for (int i = 0; i < len; i++) {
                        char c = value[i];
                        System.out.print(c);
                    }
                    System.out.println();
                }
            }
        }
        

字符输入缓冲流(过滤流)

  • BufferedReader
    • 字符过滤流
      • 提供了缓冲功能
      • 可以一行一行的读取内容
        • public String readLine();
  • 完整的字符输入流的开发步骤:

    • 创建节点流
    • 利用节点流创建字符流
    • 在字符流的基础上封装过滤流
    • 读/写数据
    • 关闭外层流

      public class TestBufferedReader {
          public static void main(String args[]) throws Exception {
              InputStream is = new FileInputStream("oracle.txt");
              InputStreamReader ir = new InputStreamReader(is);
              BufferedReader br = new BufferedReader(ir);
      
              String value = null;
              while ((value = br.readLine()) != null) {
                  System.out.println(value);
              }
          }
      }
      

      /**
      *ABC
      **/

字符输出缓冲流(过滤流)

  • PrintWriter
    • 字符过滤流
    • 提供了缓冲功能
    • 可以一行一行的输出内容
      • println();
  • 第一种用法,比较灵活的方式

    • 1.将新内容追加到文件中
    • 2.指定字符编码时utf-8;

      public class TestPrinterWriter1{
          public static void main(String[] args) {
              try (
                  OutputStream output = new FileOutputStream("abc.txt", true);
                  Writer writer = new OutputStreamWriter(output, "utf-8");
                  PrintWriter printWriter = new PrintWriter(writer);
              ){
                  printWriter.println("Hello");
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
      
  • 第二种用法 :比较简单的方式

    public static void main(String[] args) {
        try (
            PrintWriter printWriter = new PrintWriter("abc.txt", "utf-8");
        ) {
            printWriter.println("Hello 李某某2");
        } catch (Exception e) {
            e.printStackTrace();
            }
        }
    }
    

对象流及对象序列化

  • ObjectStream
    • ObjectInputStream
    • ObjectOutputStream
  • ObjectStream特点
    • writeObject()
    • readObject()
  • 对象序列化
    • 把Java对象转换为字节序列的过程称为对象的序列化
  • 对象的反序列化
    • 把字节序列恢复为Java对象的过程称为对象的反序列化

对象序列化

  • java.io.Serializable接口

     class Student implements Serializable{
        String name;
        int age;
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    

        Student stu1 = new Student("tom", 18);
        Student stu2 = new Student("jerry", 18);

        FileOutputStream fout = new FileOutputStream("stu.dat");
        ObjectOutputStream oout = new ObjectOutputStream(fout);

        oout.writeObject(stu1);
        oout.writeObject(stu2);
        oout.close();

        FileInputStream fin = new FileInputStream("stu.dat");
        ObjectInputStream oin = new ObjectInputStream(fin);

        Student s1 = (Student) oin.readObject();
        Student s2 = (Student) oin.readObject();

        oin.close();

        System.out.println(s1.name + " " + s1.age);
        System.out.println(s2.name + " " + s2.age);
  • transient 关键字标注的属性不会被序列化
  • 静态的属性不会被序列化
  • 序列化时注意事项
    • 如果一个对象的属性又是一个对象,则要求这个属性对象也实现了Serializable接口

Properties类

  • 主要用于读取项目的配置文件,配置文件以.properties结尾的文件和xml文件
  • Properties
    • Properties()
    • Properties(Properties defaults)
  • 常用方法
    • void load(InputStream inStream)
    • String getProperty(String key)
  • 创建mytest.properties

    mykey=myValue
    name=java
    address=\u5317\u4EAC
    
  • 读取配置文件

     public class TestProperties1 {
        public static void main(String[] args) throws Exception {
            Properties properties = new Properties();
            InputStream is = new FileInputStream("mytest.properties");
            properties.load(is);
    
            String myValue = properties.getProperty("mykey");
            String name = properties.getProperty("name");
            String address = properties.getProperty("address");
            String error = properties.getProperty("error"); // 没有error这个key
    
            System.out.println(myValue);// myValue
            System.out.println(name);// java
            System.out.println(address);// 北京
            System.out.println(error);// null
        }
    }
    

    /**
    *myValue
    *java
    *北京
    *null
    **/

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苦修的木鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值