Java学习--day04

io流

  • java.io.File类的使用
  • java.io.File类:计算机操作系统中的文件和文件夹。
    • File能新建、删除、重命名文件和目录,但File不能访问文件内容本身。如果
    • 需要访问文件内容本身,则需要使用输入/输出流。
    • 主要操作:
      File f =new File(“D:\myfile\java\J2SE\day01.txt”);
      //注意,\在文件中是路径的分隔符,但是在java编程中一个\的意思是转义符,在java中\或者/才是文件的分隔符
      //也可以用File.separator作为文件分隔符
 //获取文件名或者获取当前文件夹的名称
  f.getName();
  //获取文件或者文件名的路径,new file写的路径
  f.getPath();
  //获取文件或者文件名的绝对路径
  f.getAbsolutePath();
  //返回一个用当前文件绝对路径构建的file对象
  f.getAbsoluteFile();
  //返回当前文件或文件夹一个父级路径
  f.getParent();
  //给文件或文件夹重命名
  f.renameTo(new File("D:\\myfile\\java\\J2SE\\day01.txt"));
  //判断文件或者文件夹是否存在
  f.exists();
  //判断是否为可读、可写的
  f.canRead();
  f.canWrite();
  //判断当前file对象是否为文件
  f.isFile();
  //判断当前file对象是否为文件夹
  f.isDirectory();
  //获取文件最后修改时间,返回的是毫秒数
  f.lastModified();
  //获取文件长度,单位是字节数
  f.length;
  //创建文件
  File f1 = new File("D:\\myfile\\java\\J2SE\\test.txt");
  if(!f1.exists()){
      try {
          f1.createNewFile();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  //删除文件
  f1.delete();
  //创建单层路径
  File f2 = new File("D:\\myfile\\java\\J2SE\\test");
  f2.mkdir();
  //创建多层目录
  f2.mkdirs();
  //返回当前文件夹的子集名称,包括目录和文件
  String[] s =f2.list();
  for (String s1 : s) {
      System.out.println(s1);
  }
  //返回当前文件夹的子集对象,包括目录和文件
  File []f3 = f2.listFiles();
//遍历文件(递归):
public void test(File file){
  if(file.isFile()){
    System.out.println(file.getName()+"是文件");
  }else {
    System.out.println(file.getName()+"是文件夹");
    File[] f1 = file.listFiles();
    if(f1 != null && f1.length != 0){
        for(File f11:f1){
            test(f11);
        }
    }
  }
}
  • IO原理及流的分类:
    • IO原理:io六用来处理设备之间的数据传输。java程序中,对于数据的输入/输出
      操作以“流”的方式进行
    • Java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法
      输入或输出。
    • 文件流(基于硬盘)
      • 文件字节流
//文件字节输入流:
public static void testFileInputStream(){
       try {
         FileInputStream in = new FileInputStream("D:\\myfile\\java\\J2SE\\test\\test.txt");
         byte[] b =new byte[10];
         int len = 0;
         while ((len = in.read(b)) != -1) {//in.read()返回数据的长度,当为-1时读取结束
             System.out.println(new String(b,0,len));//new String(b,0,len),参数1是缓冲数据的数组,参数2是从数组的哪个位置开始转换字符串,参数3是总共转化几个字节。

         }
         in.close();//流使用完毕之后一定要关闭。
     } catch (Exception e) {
         e.printStackTrace();
       }
     }
// 文件字节输出流
public static void testFileOutputStream(){
       try {
         FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\J2SE\\test\\test1.txt");
         String s ="112321312";
         out.write(s.getBytes());//把数据卸载内存里
         out.flush();//把内存里的数据写在硬盘里
         out.close();
       } catch (Exception e) {
         e.printStackTrace();
         }
}
// 字节流复制文件
public static void copyFile(String inputpath, String outputpath) {
       try {
         FileInputStream in = new FileInputStream(inputpath);
         FileOutputStream out = new FileOutputStream(outputpath);
         byte[] b = new byte[10];
         int len = 0;
         while ((len = in.read(b)) != -1) {
             out.write(b,0,len);//写入内存
             out.flush();//刷入硬盘
         }
         out.close();//关闭输出流
         in.close();//关闭输入流
       } catch (Exception e) {
         e.printStackTrace();
       }
}
/* 文件字节流非常通用,可以用来操作字符的文档,还可以操作任何的其他类型文件(图片、压缩包等等)。
   因为字节流用的是二进制。

 文件字符流:
   和字节流差不多,把byte[]改为char[]即可。
   只适合字符类型的文件。
   在写入文件时,如果有同名文件将被覆盖。
   在读取文件时,必须保证改文件已存在,否则出异常。
*/
  • 处理流
  • 缓冲流(基于内存):
    为了能够提高数据读写的速度,一定程度上绕过硬盘的限制,java提供一种缓冲流来实现。
    就是先把数据缓冲内存里,在内存中做io操作。
    • 缓冲字节流:
//缓冲字节输入流:
        public static void testBufferedInputStream ()throws Exception {
          FileInputStream in = new FileInputStream("D:\\myfile\\java\\J2SE\\test\\test1.txt");

          BufferedInputStream bi = new BufferedInputStream(in);
          int len = 0;
          byte[] b = new byte[10];
          while((len = bi.read(b))!= -1){
              System.out.println(new String(b,0,len));
          }
          bi.close();
          in.close();
        }
//缓冲字节输出流:
         public static void testBufferedOutputStream()throws Exception{
          FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\J2SE\\test\\test2.txt");
          BufferedOutputStream bo = new BufferedOutputStream(out);

          String s ="12345565";
          bo.write(s.getBytes());
          bo.flush();
          bo.close();
          out.close();
        }
//复制文件:
        public static void copyFile() throws Exception{
          BufferedInputStream bi = new BufferedInputStream(new FileInputStream("D:\\myfile\\java\\J2SE\\test\\test1.txt"));
          BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream("D:\\myfile\\java\\J2SE\\test\\test3.txt"));
          int len = 0 ;
          byte[] b =new byte[1024];
          while ((len = bi.read(b)) != -1) {
              bo.write(b,0,len);
              bo.flush();
          }
          bo.close();
          bi.close();
        }
//缓冲字符流: 将byte[] 换做char[],BufferedReader,BufferedeWriter.
  • 转换流
  • 应用场景:当字节流都为字符时,转换为字符流更高效。
/**
 *转换输入流
 * @throws Exception
 */
 public static void testInputStreamReader()throws Exception{
     FileInputStream in = new FileInputStream("D:\\myfile\\java\\J2SE\\test\\test.txt");
     InputStreamReader ir = new InputStreamReader(in,"utf-8");

     char[] c = new char[100];
     int len = 0;

     while ((len = ir.read(c)) != -1) {
         System.out.println(new String(c,0,len));
     }
     ir.close();
     in.close();
 }

/**
* 转换输出流
* @throws Exception
*/
public static void testOutputStreamWriter()throws Exception{
    FileOutputStream out = new FileOutputStream("D:\\myfile\\java\\J2SE\\test\\test1.txt");
    OutputStreamWriter ow = new OutputStreamWriter(out,"utf-8");
    String s = "转换输出流";
    ow.write(s);
    ow.flush();
    ow.close();
    out.close();
}
  • 标准输入输出流:
 public static void test1() throws Exception {
      InputStreamReader ir = new InputStreamReader(System.in);//转换输入流,将字节输入流转换成字符输入流
      BufferedReader br = new BufferedReader(ir);//缓冲字符输入流
      BufferedWriter bt = new BufferedWriter(new FileWriter("D:\\myfile\\java\\J2SE\\test\\test.txt"));//缓冲字符输出流
      String str = "";
      while ((str = br.readLine()) != null) {
          if (str.equals("over")) {
              break;
          }
          bt.write(str);
      }
      bt.flush();
      bt.close();
      br.close();
      ir.close();
    }
  • 打印流
    System.out.println();
  • 数据流
/**
    *数据输出流
    */
public static void testDataOutputStream() throws Exception{
    DataOutputStream ds = new DataOutputStream(new FileOutputStream("D:\\myfile\\java\\J2SE\\test\\test3.txt"));
    ds.writeDouble(1.35d);

    ds.flush();
    ds.close();
}
/**
* 数据输入流,与数据输出流的类型要一致才能显示
*/
public static void testDataInputStream() throws Exception{
    DataInputStream in = new DataInputStream(new FileInputStream("D:\\myfile\\java\\J2SE\\test\\test3.txt"));
    System.out.println(in.readDouble());
    in.close();
}
  • 对象流
  • 序列化:用ObjectOutputStream类将一个Java对象写入io流中。
  • 反序列化:用ObjectInputStream类从io流中恢复对Java对象。
  • 序列化和反序列化针对的都是对象的各种属性,不包括类的属性。
  • 如果要让一个对象支持序列化机制,那么必须实现如下两个接口之一:Serializable、Externalizable
/**
* 序列化对象
*/
public static void testSerialize() throws Exception{
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\myfile\\java\\J2SE\\test\\test.txt")) ;
    Person p = new Person();
    p.age = 1;
    p.name= "张三";
    out.writeObject(p);

    out.flush();
    out.close();
}

/**
* 反序列化对象,此时反序列化的对象必须和序列化对象的类保持一致(同一个包)
*/
public static void testDeSerialize() throws Exception{
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\myfile\\java\\J2SE\\test\\test.txt"));
    Object obj = in.readObject();

    Person p = (Person)obj;

    System.out.println(p.age);
    System.out.println(p.name);
    in.close();
}
  • 随机存取流
/**
* 随机取
* @throws Exception
*/
public static void testRandomAccessFileReader() throws Exception{
    RandomAccessFile ra = new RandomAccessFile("D:\\myfile\\java\\J2SE\\test\\test1.txt","r");

    ra.seek(0);//设置读取文件内容的起始点,来达到从文件的任意位置读取
    int len = 0;
    byte[] b = new byte[1024];
    while ((len = ra.read(b)) != -1) {
        System.out.println(new String(b,0,len));
    }
    ra.close();
}
/**
* 随机写
*/
public static void testRandomAccessFileWriter() throws Exception{
    RandomAccessFile ra = new RandomAccessFile("D:\\myfile\\java\\J2SE\\test\\test1.txt","rw");

// ra.seek(0);//从起始位置开始写,会覆盖掉字符
    ra.seek(ra.length());//从最后位置开始写

    ra.write("你好".getBytes());
    ra.close();
}
  • 小结:处理数据时,一定要明确数据源,与数据目的地,流只是在帮助数据进行传输,并帮助处理数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Wucy0127

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

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

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

打赏作者

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

抵扣说明:

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

余额充值