文件操作——File

File

1.学习File之前,最好了解一些关于内存的知识(CPU,内存,硬盘)
2.Java API (java.io.File)支持访问硬盘文件

File基础学习

1.java.io.File:该类用于描述文件系统中的一个文件或目录。


File可以

1.访问文件或目录的属性信息**
- (1.)获取文件或目录名
- (2.)获取文件长度(字节)
- (3.)最后修改时间

代码案例:

public class FileDemo1{
    public static void main(String[] args){
        /*
         *路径尽量不写绝对路径,常用的是使用相对路径;
         *1.相对于项目目录(当前目录)
         *2.相对于类加载目录(实际开发更常用)
         */
         //File file = new File("./test.txt");当前项目目录
         File file = new File("."+File.separator+"test.txt");
         /*
          *获取当前文件的属性信息
          */
          //获取文件或目录名
         String name = file.getName();
         System.out.println(name);
         //获取文件长度(字节)
         long length = file.length();
         System.out.println("length:"+length+"字节");
         //最后修改时间
         long time = file.lastModified();
         //System.out.println(time);
         Date date = new Date(time);
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd,H:m:s");
         System.out.println("最后修改时间"+sdf.format(date));
    }
    /*
     * 可读,可写,可运行
     */
     file.canRead();
     file.canExcute();
     boolean canWrite = file.canWrite();
     System.out.println("只读:"+canWrite);

    boolean isHidden = file.isHidden()
    System.out.println("隐藏:"+isHidden);
}
2.访问一个目录中的所有子项**

代码案例:

  /**
   * 获取一个目录的所有子项
   */
   public class FileDemo7{
        public static void main(String[] args){
        /*
         * 获取当前目录下的所有内容
         */ 
         File dir = new File(".");
         /*
          * boolean isFile()
          * 判断当前File对象表示的是否为一个文件
          * 
          * boolean isDirectory()
          * 判断是否表示的是一个目录
          */    
          if(dir.isDirectory()){
                File[] subs = dir.listFiles();
                for(File sub:subs){
                    if(sub.isFile()){
                     System.out.print("文件:");
                    }else{
                     System.out.print("目录:");
                    }
                System.out.println(sub.getName());  
                }
            }
        }
    }

/**
 * 获取一个目录中的部分子项,File支持一个
 * 重载的listFiles方法,要求传入一个文件
 * 过滤器,这样只会返回该目录中满足该过滤器
 * 要求的子项。
 */
 public class FileDemo8{
    public static void main(String[] args){
        /*
         * 仅获取当前目录的全部文件
         */
         File dir = new File(".");
         MyFilter filter = new MyFilter();
         File[] subs = dir.listFiles(filter);
         for(File sub:subs){
            System.out.println(sub.getName());
        }
    }       
}
class MyFilter implements File{
    public boolean accept(File file){
        System.out.println("正在过滤:"+file.getName());
        return file.isFile();
    }
}
3.操作文件或目录(创建,删除)**

代码案例(文件的创建,删除):

    /**
     * 使用File创建文件
     */ 
public class FileDemo2{
    public static void main(String[] args)throws IOException
    /*
     * 在当前目录下创建demo.txt文件
     * 不写"./" 默认就是在当前目录下
     */
     File file = new File("demo.txt");
     /*
      * 判断File表示的文件或目录是否真实存在
      */
      if(!file.exists()){
        file.createNewFile();
        System.out.println("创建完毕");
    }else{
        System.out.println("改文件已经存在");
    }
}

/**
 * 删除文件
 */
public class FileDemo3{
    public static void main(String[] args){
        /*
         * 将当前目录中的demo.txt文件删除
         */
         File file = new File("demo.txt");
         if(file.exists()){
            file.delete();
            System.out.println("删除成功");
        }else{
            System.out.println("不存在此文件");
        }
    }
}

代码案例(目录的创建,删除):

    /**
     * 创建一个目录
     */
 public class FileDemo4{
     /*
      * 在当前目录下创建目录demo
      */
    public static void main(String[] args){
        File dir = new File("demo");
        if(!dir.exists()){
            dir.mkdir();
            System.out.println("创建完毕");
        }else{
            System.out.println("该目录已经存在!");
        }
    }
}   

/**
 * 常见多级目录
 */ 
 public class FileDemo5{
    public static void main(String[] args){
        /*
         * 在当前目录下创建a/b/c/d/e/f目录
         */
         File file = new File(
            "a"+File.separator+
            "b"+File.separator+
            "c"+File.separator+
            "d"+File.separator+
            "e"+File.separator+
            "f"
        );
        if(!dir.exits()){
            /*
             * 该方法会将所有不存在的父目录一同创建出来
             */
             dir.mkdirs();
             System.out.println("创建成功!");
        }else{
            System.out.println("该目录已经存在");
        }
    }
}

/**
 * 删除目录
 */
 public class FileDemo6(){
    public static void main(String[] args){
        File dir = new File("demo");
        if(dir.exists){
            /*
             * 删除目录要求该目录必须是一个空目录
             */
            dir.delete();
            System.out.println("删除完毕!");
        }
    }   
 }

/**
 * 定义一个方法,可以删除指定的文件或者目录
 */
 public class Test{
    public static void main(String[] args){
        File dir = new File("a");//这里的a是一个多层的目录
        delete(dir);
    }
/**
 * 将给定的File表示的文件或目录删除
 */
public static void delete(File file){
    if(file.isDirectory()){
    File[]  subs= file.listFiles();
    for(File sub:subs){
        delete(sub);
    }
    file.delete();
  }
}

注意:File不可以访问文件数据


RandomAccessFile

代码案例:

    /**
     * java.io.RandomAccessFile 用于读写文件数据。
     * 其基于指针对文件进行读写。创建RandomAccessFile有两种常用模式:
     * 1."r",即只读模式,仅对文件数据进行读写操作。
     * 2."rw",即读写模式,对文件数据可以编辑。
     */
public static void main(String[] args)throws IOException{
    /*
     * RandomAccessFile(File f,String mode)
     * RandomAccessFile(String path,String mode);
     */
    RandomAccessFile raf = new RandomAccessFile("raf.dat","rw");
     /*
      * void write(int d)
      * 写出一个字节,写出的是该整数对应的二进制中的"低八位"
      *                            vvvvvvvv
      * 00000000 00000000 00000000 00000001
      */
      //char a = '1';
      //ind d = (int)a;
      //System.out.println(d);
      //raf.write(49);
      raf.write(97);//a
      raf.write(98);//b
      raf.write(99);//c
      /*
       * raf.dat中的文件数据有三个字节了,内容为:
       * 01100001 01100010 01100011
       */
       /*
        * 读写完毕后关闭raf
        */
       raf.close(); 
}

---

**读取字节**
public class RandomAccessFileDemo2{
    public static void main(String[] args)throws IOException{
        RandomAccessFile raf = new RandAccessFile("raf.dat","r");
        /*
         * int read()
         * 从文件中指针当前位置读取该字节,并以10进制的数组形式返回。
         * 若返回值为-1,则表示读取到了文件末尾。
         */
         int d = raf.read();
         System.out.println(d);//97

         d = raf.read();
         System.out.println(d);//98

        d = raf.read();
        System.out.println(d);//99

        d = raf.read();
        System.out.println(d);//-1
        raf.close();
    }
}

---
**读写基本类型数据**
/**
 * RandomAccessFile 读写基本类型数据以及基于指针的读写操作
 */ 
 public class RandomAccessFileDemo3{
    public static void main(String[] args){
        /*
         * RAF总是在指针当前位置进行读写字节,并且无论进行了读
         * 还是写一个字节后,指针都会自动向后移动到下一个字节的
         * 位置。
         * 默认创建出来RAF时,指针的位置为0,即:文本的第一个
         * 字节的位置。
         */
         //获取当前指针的位置
         long pos = raf.getFilePointer();
         System.out.println("pos:"+pos);
         /*
          * 写入一个int最大值
          * 01111111 11111111 11111111 11111111
          */
          int imax = Integer.MAX_VALUE;
          System.out.println(imax);
          raf.write(imax>>>24);
          System.out.println("pos:"+raf.getFilePointer());
          raf.write(imax>>>16);
          raf.write(imax>>>8);
          raf.write(imax);
          /*
           * 一次写出4个字节,将int值写出
           */
           System.out.println("pos:"+raf.getFilePointer());
           raf.writeInt(imax);

           raf.writeLong(123L);

           raf.writeDouble(123.123);
           System.out.println("写出完毕!");
            /*
             * void seek(long pos)
             * 将指针移动到指定位置
             */
             //将指针移动到文件开始出
             raf.seek(0);
             System.out.println("pos:"+raf.getFilePointer());//0

        /*
         * int readInt()
         * 连续读取4个字节,并且转换为对应的int值返回,若在读取的4个字节的
         * 过程中 读取到文件末尾,则会抛出EOFException
         */ 
         int max = raf.readInt();
         System.out.println(max);
         System.out.println("pos:"+raf.getFilePointer());//4

        //读取double
        raf.seek(16);
        double d = raf.readDouble();
        System.out.println(d);
        System.out.println("pos:"+raf.getFilePointer());

        //读取long
        raf.seek(8);
        long l = raf.readLong();
        System.out.println(l);
        raf.close();
    }
 } 

---
**读写字符串**
public class RandomAccessFileDemo4{
    public static void main(String[] args){
        RandomAccessFile raf = new RandomAccessFile("raf.txt","rw");

    String str = "大连今天下雨了";
    //字符集(GBK UTF-8)
    /*
     * String提供了将当前字符串转换为字节的方法
     * byte[] getBytes();
     * 将当前字符串按照默认字符集转换
     * 
     * byte[] getBytes(String csn)
     * 将当前字符串按照给定的字符集转换
     * 字符集的名字不区分大小写
     */
     byte[] data = str.getBytes("GBK");
     raf.write(data);

     System.out.println("pos:"+raf.getFilePointer());

    raf.seek(0);
    byte[] buf = new byte[30];
    int len = raf.read(buf);
    System.out.println(len);

    String s = new String(buf,0,len,"GBK");
    System.out.println(s);

    raf.close();    
    }
}

复制文件

代码案例:

    /**
     * 复制文件
     */  
public class CopyDemo1{
    public static void main(String[] args)throws IOException{
            RandomAccessFile src = new RandomAccessFile("music.mp3","r");

            RandomAccessFile desc = new RandomAccessFile("music_cp.mp3","rw");
            long start = System.currentTimeMillis();
            int d = -1;
            while((d=src.read())!=-1){
                desc.write(d);
            }
            long end = System.currentTimeMillis();
            System.out.println("复制完毕耗时:"+(end-start));
            src.close();
            desc.close();
    }
}   

---
/**
 * 若希望提高读写效率,需要提高每次读写的数据量
 * 来减少读写次数从而达到提高读写效率的目的
 */
 public class CopyDemo2{
    public static void main(String[] args)throws IOException{
        RandomAccessFile src = new RandomAccessFile("music.mp3","r");
        RandomAccessFile desc = new RandomAccessFile("music_cp.mp3","rw");

        /*
         * int read(byte[] d)
         * 一次性读取给定的数组总长度的字节量,并存入到该数据中,
         * 返回值为实际读取到的字节量。若返回值为-1,则表示读取
         * 到了文件末尾(EOF end of file)
         */
         int len = -1//记录每次读取到的实际字节量
         byte[] buf = new byte[1024*10];//10k
  long start = System.currentTimeMillis();
  when((len=src.read(buf))!=-1){
        /*
         * void write(byte[] d)
         * 将给定的字节数组中的左右字节一次性写入到文件中
         * 
         * void write(byte[] d,int offset,int len)
         * 将给定的字节数组中从下标的offset处的字节开始
         * 连续len个字节一次性写入到文件中
         */
         raf.write(buf,0,len);
        }
        long end = System.currentTimeMillis();
        System.out.println("辅助完毕耗时:"+(end-start));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值