zoukankan      html  css  js  c++  java
  • Java开发之File类

    File类

    File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。

    【案例 】创建一个文件

     1 import java.io.*;
     2 class hello{
     3    public static void main(String[] args) {
     4        File f=new File("D:\hello.txt");
     5        try{
     6            f.createNewFile();
     7        }catch (Exception e) {
     8            e.printStackTrace();
     9        }
    10     }
    11 }

    【案例2】File类的两个常量

    1 import java.io.*;
    2 class hello{
    3    public static void main(String[] args) {
    4        System.out.println(File.separator);
    5        System.out.println(File.pathSeparator);
    6     }
    7 }

    此处多说几句:有些同学可能认为,我直接在windows下使用进行分割不行吗?当然是可以的。但是在linux下就不是了。所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。

    【案例3】File类中的常量改写案例1的代码:

     1 import java.io.*;
     2 class hello{
     3    public static void main(String[] args) {
     4        String fileName="D:"+File.separator+"hello.txt";
     5        File f=new File(fileName);
     6        try{
     7            f.createNewFile();
     8        }catch (Exception e) {
     9            e.printStackTrace();
    10        }
    11     }
    12 }

    【案例4】删除一个文件(或者文件夹)

     1 import java.io.*;
     2 class hello{
     3    public static void main(String[] args) {
     4        String fileName="D:"+File.separator+"hello.txt";
     5        File f=new File(fileName);
     6        if(f.exists()){
     7            f.delete();
     8        }else{
     9            System.out.println("文件不存在");
    10        }
    11          
    12     }
    13 }

    【案例5】创建一个文件夹

     1 /**
     2  * 创建一个文件夹
     3  * */
     4 import java.io.*;
     5 class hello{
     6    public static void main(String[] args) {
     7        String fileName="D:"+File.separator+"hello";
     8        File f=new File(fileName);
     9        f.mkdir();
    10     }
    11 }

    【案例6】列出目录下的所有文件

     1 /**
     2  * 使用list列出指定目录的全部文件
     3  * */
     4 import java.io.*;
     5 class hello{
     6    public static void main(String[] args) {
     7        String fileName="D:"+File.separator;
     8        File f=new File(fileName);
     9        String[] str=f.list();
    10        for (int i = 0; i < str.length; i++) {
    11            System.out.println(str[i]);
    12        }
    13     }
    14 }

    注意使用list返回的是String数组,。而且列出的不是完整路径,如果想列出完整路径的话,需要使用listFiles.它返回的是File的数组。

    【案例7】列出指定目录的全部文件(包括隐藏文件):

     1 /**
     2  * 使用listFiles列出指定目录的全部文件
     3  * listFiles输出的是完整路径
     4  * */
     5 import java.io.*;
     6 class hello{
     7    public static void main(String[] args) {
     8        String fileName="D:"+File.separator;
     9        File f=new File(fileName);
    10        File[] str=f.listFiles();
    11        for (int i = 0; i < str.length; i++) {
    12            System.out.println(str[i]);
    13        }
    14     }
    15 }

    【案例8】判断一个指定的路径是否为目录

     1 /**
     2  * 使用isDirectory判断一个指定的路径是否为目录
     3  * */
     4 import java.io.*;
     5 class hello{
     6    public static void main(String[] args) {
     7        String fileName="D:"+File.separator;
     8        File f=new File(fileName);
     9        if(f.isDirectory()){
    10            System.out.println("YES");
    11        }else{
    12            System.out.println("NO");
    13        }
    14     }
    15 }

    【案例9】递归搜索指定目录的全部内容,包括文件和文件夹

     1 import java.io.File;
     2 
     3 public class Hello {
     4     /**
     5      * 列出指定目录的全部内容
     6      */
     7     public static void main(String[] args) {
     8         String fileName = "D:" + File.separator;
     9         File f = new File(fileName);
    10         print(f);
    11     }
    12 
    13     private static void print(File f) {
    14         if (f != null) {
    15             if (f.isDirectory()) {
    16                 File[] fileArray = f.listFiles();
    17                 if (fileArray != null) {
    18                     for (int i = 0; i < fileArray.length; i++) {
    19                         print(fileArray[i]);
    20                     }
    21                 } else {
    22                     System.out.println(f);
    23                 }
    24             }
    25         }
    26     }
    27 
    28 }

    10.RandomAccessFile类
    该对象并不是流体系中的一员,其封装了字节流,同时还封装了一个缓冲区(字符数组),通过内部的指针来操作字符数组中的数据。该对象特点:
    该对象只能操作文件,所以构造函数接收两种类型的参数:a.字符串文件路径;b.File对象。
    该对象既可以对文件进行读操作,也能进行写操作,在进行对象实例化时可指定操作模式(r,rw)
    注意:该对象在实例化时,如果要操作的文件不存在,会自动创建;如果文件存在,写数据未指定位置,会从头开始写,即覆盖原有的内容。可以用于多线程下载或多个线程同时写数据到文件。
    【案例】使用RandomAccessFile写入文件

     1 /**
     2  * 使用RandomAccessFile写入文件
     3  * */
     4 import java.io.*;
     5 class hello{
     6     public static void main(String[]args) throws IOException {
     7         StringfileName="D:"+File.separator+"hello.txt";
     8         File f=new File(fileName);
     9         RandomAccessFile demo=newRandomAccessFile(f,"rw");
    10        demo.writeBytes("asdsad");
    11         demo.writeInt(12);
    12         demo.writeBoolean(true);
    13         demo.writeChar('A');
    14         demo.writeFloat(1.21f);
    15         demo.writeDouble(12.123);
    16         demo.close();  
    17     }
    Java IO流的高级概念
    编码问题
    【案例 】取得本地的默认编码
    1 /**
    2  * 取得本地的默认编码
    3  * */
    4 publicclass CharSetDemo{
    5     public static void main(String[] args){
    6         System.out.println("系统默认编码为:"+ System.getProperty("file.encoding"));
    7     }
    8 }

    【案例 】乱码的产生

     1 import java.io.File;
     2 import java.io.FileOutputStream;
     3 import java.io.IOException;
     4 import java.io.OutputStream;
     5   
     6 /**
     7  * 乱码的产生
     8  * */
     9 public class CharSetDemo2{
    10     public static void main(String[] args) throws IOException{
    11         File file = new File("d:" + File.separator + "hello.txt");
    12         OutputStream out = new FileOutputStream(file);
    13         byte[] bytes = "你好".getBytes("ISO8859-1");
    14         out.write(bytes);
    15         out.close();
    16     }//输出结果为乱码,系统默认编码为GBK,而此处编码为ISO8859-1
    对象的序列化</h2>
    对象序列化就是把一个对象变为二进制数据流的一种方法。
    一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。先让我们实现一个具有序列化能力的类吧:
    【案例 】实现具有序列化能力的类
     1 import java.io.*;
     2 /**
     3  * 实现具有序列化能力的类
     4  * */
     5 public class SerializableDemo implements Serializable{
     6     public SerializableDemo(){
     7          
     8     }
     9     publicSerializableDemo(String name, int age){
    10         this.name=name;
    11         this.age=age;
    12     }
    13     @Override
    14     public String toString(){
    15         return "姓名:"+name+"  年龄:"+age;
    16     }
    17     private String name;
    18     private int age;
    19 }

    【案例 】序列化一个对象 – ObjectOutputStream

     1 import java.io.Serializable;
     2 import java.io.File;
     3 import java.io.FileOutputStream;
     4 import java.io.IOException;
     5 import java.io.ObjectOutputStream;
     6 /**
     7  * 实现具有序列化能力的类
     8  * */
     9 public class Person implements Serializable{
    10     public Person(){
    11      }
    12     public Person(String name,int age){
    13         this.name = name;
    14         this.age = age;
    15     }
    16     @Override
    17     public String toString(){
    18         return "姓名:" +name + "  年龄:" +age;
    19     }
    20     private String name;
    21     private int age;
    22 }
    23 /**
    24  * 示范ObjectOutputStream
    25  * */
    26 public class ObjectOutputStreamDemo{
    27     public static voidmain(String[] args) throws IOException{
    28         File file = newFile("d:" + File.separator + "hello.txt");
    29         ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(
    30                 file));
    31         oos.writeObject(newPerson("rollen", 20));
    32         oos.close();
    33     }
    34 }

    【案例 】反序列化—ObjectInputStream

     1 import java.io.File;
     2 import java.io.FileInputStream;
     3 import java.io.ObjectInputStream;
     4   
     5 /**
     6  * ObjectInputStream示范
     7  * */
     8 public class ObjectInputStreamDemo{
     9     public static voidmain(String[] args) throws Exception{
    10         File file = new File("d:" +File.separator + "hello.txt");
    11         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
    12                 file));
    13         Object obj =input.readObject();
    14         input.close();
    15         System.out.println(obj);
    16     }
    17 }
    注意:被Serializable接口声明的类的对象的属性都将被序列化,但是如果想自定义序列化的内容的时候,就需要实现Externalizable接口。
    当一个类要使用Externalizable这个接口的时候,这个类中必须要有一个无参的构造函数,如果没有的话,在构造的时候会产生异常,这是因为在反序列话的时候会默认调用无参的构造函数。
    现在我们来演示一下序列化和反序列话:
    【案例 】使用Externalizable来定制序列化和反序列化操作
     1 import java.io.Externalizable;
     2 import java.io.File;
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.ObjectInput;
     7 import java.io.ObjectInputStream;
     8 import java.io.ObjectOutput;
     9 import java.io.ObjectOutputStream;
    10   
    11 /**
    12  * 序列化和反序列化的操作
    13  * */
    14 public class ExternalizableDemo{
    15     public static voidmain(String[] args) throws Exception{
    16         ser(); // 序列化
    17         dser(); // 反序列话
    18     }
    19   
    20     public static void ser()throws Exception{
    21         File file = newFile("d:" + File.separator + "hello.txt");
    22         ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
    23                 file));
    24         out.writeObject(newPerson("rollen", 20));
    25         out.close();
    26     }
    27   
    28     public static void dser()throws Exception{
    29         File file = newFile("d:" + File.separator + "hello.txt");
    30         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
    31                 file));
    32         Object obj =input.readObject();
    33         input.close();
    34        System.out.println(obj);
    35     }
    36 }
    37   
    38 class Person implements Externalizable{
    39     public Person(){
    40   
    41     }
    42   
    43     public Person(String name,int age){
    44         this.name = name;
    45         this.age = age;
    46     }
    47   
    48     @Override
    49     public String toString(){
    50         return "姓名:" +name + "  年龄:" +age;
    51     }
    52   
    53     // 复写这个方法,根据需要可以保存的属性或者具体内容,在序列化的时候使用
    54     @Override
    55     public voidwriteExternal(ObjectOutput out) throws IOException{
    56        out.writeObject(this.name);
    57         out.writeInt(age);
    58     }
    59   
    60     // 复写这个方法,根据需要读取内容 反序列话的时候需要
    61     @Override
    62     public voidreadExternal(ObjectInput in) throws IOException,
    63            ClassNotFoundException{
    64         this.name = (String)in.readObject();
    65         this.age =in.readInt();
    66     }
    67   
    68     private String name;
    69     private int age;
    70 }
    注意:Serializable接口实现的操作其实是吧一个对象中的全部属性进行序列化,当然也可以使用我们上使用是Externalizable接口以实现部分属性的序列化,但是这样的操作比较麻烦,
    当我们使用Serializable接口实现序列化操作的时候,如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明:
    【案例 】使用transient关键字定制序列化和反序列化操作
     1 import java.io.File;
     2 import java.io.FileInputStream;
     3 import java.io.FileOutputStream;
     4 import java.io.ObjectInputStream;
     5 import java.io.ObjectOutputStream;
     6 import java.io.Serializable;
     7   
     8 /**
     9  * 序列化和反序列化的操作
    10  * */
    11 public class serDemo{
    12     public static voidmain(String[] args) throws Exception{
    13         ser(); // 序列化
    14         dser(); // 反序列话
    15     }
    16   
    17     public static void ser()throws Exception{
    18         File file = newFile("d:" + File.separator + "hello.txt");
    19         ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(
    20                 file));
    21         out.writeObject(newPerson1("rollen", 20));
    22         out.close();
    23     }
    24   
    25     public static void dser()throws Exception{
    26         File file = newFile("d:" + File.separator + "hello.txt");
    27         ObjectInputStreaminput = new ObjectInputStream(new FileInputStream(
    28                 file));
    29         Object obj =input.readObject();
    30         input.close();
    31        System.out.println(obj);
    32     }
    33 }
    34   
    35 class Person1 implements Serializable{
    36     public Person1(){
    37   
    38     }
    39   
    40     public Person1(Stringname, int age){
    41         this.name = name;
    42         this.age = age;
    43     }
    44   
    45     @Override
    46     public String toString(){
    47         return "姓名:" +name + "  年龄:" +age;
    48     }
    49   
    50     // 注意这里
    51     private transient Stringname;
    52     private int age;
    53 }
    【运行结果】:
    姓名:null  年龄:20
    【案例 】序列化一组对象
     
     1 import java.io.File;
     2 import java.io.FileInputStream;
     3 import java.io.FileOutputStream;
     4 import java.io.ObjectInputStream;
     5 import java.io.ObjectOutputStream;
     6 import java.io.Serializable;
     7  
     8 /**
     9  * 序列化一组对象
    10  * */
    11 public class SerDemo1{
    12     public static void main(String[] args) throws Exception{
    13         Student[] stu = { new Student("hello", 20), new Student("world", 30),
    14                 new Student("rollen", 40) };
    15         ser(stu);
    16         Object[] obj = dser();
    17         for(int i = 0; i < obj.length; ++i){
    18             Student s = (Student) obj[i];
    19             System.out.println(s);
    20         }
    21     }
    22  
    23     // 序列化
    24     public static void ser(Object[] obj) throws Exception{
    25         File file = new File("d:" + File.separator + "hello.txt");
    26         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
    27                 file));
    28         out.writeObject(obj);
    29         out.close();
    30     }
    31  
    32     // 反序列化
    33     public static Object[] dser() throws Exception{
    34         File file = new File("d:" + File.separator + "hello.txt");
    35         ObjectInputStream input = new ObjectInputStream(new FileInputStream(
    36                 file));
    37         Object[] obj = (Object[]) input.readObject();
    38         input.close();
    39         return obj;
    40     }
    41 }
    42  
    43 class Student implements Serializable{
    44     public Student(){
    45         
    46     }
    47  
    48     public Student(String name, int age){
    49         this.name = name;
    50         this.age = age;
    51     }
    52  
    53     @Override
    54     public String toString(){
    55         return "姓名:  " + name + "  年龄:" + age;
    56     }
    57  
    58     private String name;
    59     private int age;
    60 }
  • 相关阅读:
    记php多张图片合成一张图片 压缩固定分辨率 合并生成竖列 纵向长图(可用于商品详情图合并下载)
    记php-mysql分页查询出现重复数据
    记laravel order by 问题
    记登录注册时候 前端js明文密码 加密传输 php解密
    记下载oss图片接口(附带删除)
    记tp5.1使用composer PhpOffice的xlsx表格文件导入数据库
    记php移动并压缩多级目录文件为zip文件并上传oss
    Jmeter服务器性能监控工具插件之ServerAgent
    Jmeter阶梯式加压测试
    Jmeter 下载+安装+汉化+版本更新+备份使用(Jmeter 4+版本均适用)
  • 原文地址:https://www.cnblogs.com/liyiran/p/5032954.html
Copyright © 2011-2022 走看看