File类

文件和目录文件名的抽象表示。在java程序中,对磁盘文件进行描述的类。文件和目录路径名的抽象表示形式。

一、属性

//系统相关的默认名称分隔符。 此字段初始化为包含系统属性file.separator的值的第一个字符。 
   //在UNIX系统上,此字段的值为“/”; 在Microsoft Windows系统上,它是'\\'。
    public static final char separatorChar = fs.getSeparator();
     //系统相关的默认名称分隔符,表示成字符串
    public static final String separator = "" + separatorChar;
     //系统的路径分隔符字符 此字符用于分隔作为路径列表给出的文件序列中的文件名。 
     //在UNIX系统上,此字符为':'; 在Microsoft Windows系统上它是';'。
    public static final char pathSeparatorChar = fs.getPathSeparator();
     //依赖于系统的路径分隔符字符,为了方便所有表示字符串。这个字符串包含单个字符,即path分隔符。
    public static final String pathSeparator = "" + pathSeparatorChar;

二、3个公共构造方法

//通过将给定的路径名字符串转换为抽象路径名来创建新的文件实例。
public File(String pathname) {
    if (pathname == null) {
        throw new NullPointerException();
    }
    this.path = fs.normalize(pathname);
    this.prefixLength = fs.prefixLength(this.path);
}

/**
1、通过父目录路径和子路径创建File实例
2、如果parent为null,调用单参数File构造函数创建新的File实例。
3、否则,父路径名字符串用于表示目录,子路径名字符串用于表示目录或文件。 
*/    
public File(String parent, String child) {
    if (child == null) { //如果子路径为空,抛出异常
        throw new NullPointerException();
    }
    if (parent != null) { 
        if (parent.equals("")) {
            this.path = fs.resolve(fs.getDefaultParent(),
                                   fs.normalize(child));
        } else {
            this.path = fs.resolve(fs.normalize(parent),
                                   fs.normalize(child));
        }
    } else {
        this.path = fs.normalize(child);
    }
    this.prefixLength = fs.prefixLength(this.path);
}


 /**
 1、根据父抽象路径名和子路径名字符串创建新的File实例。
 2、如果parent为null,则调用单参数File构造函数根据子路径创建新的File实例。
 3、parent不为null,父抽象路径名用于表示目录,子路径名字符串用于表示目录或文件。
 */
public File(File parent, String child) {
    if (child == null) {
        throw new NullPointerException();
    }
    if (parent != null) {
        if (parent.path.equals("")) {
            this.path = fs.resolve(fs.getDefaultParent(),
                                   fs.normalize(child));
        } else {
            this.path = fs.resolve(parent.path,
                                   fs.normalize(child));
        }
    } else {
        this.path = fs.normalize(child);
    }
    this.prefixLength = fs.prefixLength(this.path);
}

//通过将给定的 file: URI转换到一个抽象路径名创建一个新的 File实例。 
public File(URI uri) {

    // Check our many preconditions
    if (!uri.isAbsolute())
        throw new IllegalArgumentException("URI is not absolute");
    if (uri.isOpaque())
        throw new IllegalArgumentException("URI is not hierarchical");
    String scheme = uri.getScheme();
    if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
        throw new IllegalArgumentException("URI scheme is not \"file\"");
    if (uri.getAuthority() != null)
        throw new IllegalArgumentException("URI has an authority component");
    if (uri.getFragment() != null)
        throw new IllegalArgumentException("URI has a fragment component");
    if (uri.getQuery() != null)
        throw new IllegalArgumentException("URI has a query component");
    String p = uri.getPath();
    if (p.equals(""))
        throw new IllegalArgumentException("URI path component is empty");

    // Okay, now initialize
    p = fs.fromURIPath(p);
    if (File.separatorChar != '/')
        p = p.replace('/', File.separatorChar);
    this.path = fs.normalize(p);
    this.prefixLength = fs.prefixLength(this.path);
}

三、常用方法

返回值方法名/描述
booleancanExecute() 测试应用程序是否可以执行此抽象路径名表示的文件。
booleancanRead() 测试应用程序是否可以读取此抽象路径名表示的文件。
booleancanWrite() 测试应用程序是否可以修改此抽象路径名表示的文件。
intcompareTo(File) 按字母顺序比较两个抽象路径名。
booleanexists() 测试此抽象路径名表示的文件或目录是否存在。
booleancreateNewFile() 当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建个新的空文件。
booleandelete() 删除此抽象路径名表示的文件或目录。
FilegetAbsoluteFile() 返回此抽象路径名的绝对路径名形式。
StringgetAbsolutePath() 返回此抽象路径名的绝对路径名字符串。
FilegetCanonicalFile() 返回此抽象路径名的规范形式。
StringgetCanonicalPath() 返回此抽象路径名的规范路径名字符串。
StringgetName() 返回由此抽象路径名表示的文件或目录的名称。
StringgetParent() 返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。
FilegetParentFile() 返回此抽象路径名父目录的抽象路径名;如果此路径名没有指定父目录则返回 null。
StringgetPath() 将此抽象路径名转换为一个路径名字符串。
booleanisDirectory() 测试此抽象路径名表示的文件是否是一个目录。
booleanisFile() 测试此抽象路径名表示的文件是否是一个标准文件。
booleanisHidden() 测试此抽象路径名指定的文件是否是一个隐藏文件。
String[]list() 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。
booleanmkdir() 创建此抽象路径名指定的目录。
booleanmkdirs() 创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。
booleanrenameTo(File dest) 重新命名此抽象路径名表示的文件。
File[]listFiles() 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。
booleansetLastModified(long time) 设置最后修改时间
booleansetReadOnly() 设置文件或文件夹为只读
booleansetWritable(boolean writable, boolean ownerOnly) 设置此抽象路径名的所有者或每个人的写入权限。
static File在默认的临时文件目录中创建一个空文件,使用给定的前缀和后缀来生成它的名称。

四、使用示例

public class FileTest {
    public static void main(String[] args) throws Exception{
        File filea = new File("f:\\a\\");
        System.out.println(filea.mkdir());//创建一个a文件夹
        System.out.println(filea.exists());//判断文件夹是都存在

        File fileb = new File("f:\\b\\c");
        System.out.println(fileb.mkdirs()); //创建多级文件夹

        File file1 = new File("f:\\a\\a.txt");//在f盘的a文件夹下创建a.txt文件
        //createNewFile方法:创建一个新的空文件(若存在则创建失败)
        System.out.println(file1.createNewFile());
        System.out.println(file1.exists());//判断文件是都存在
        //delete方法:只能删除文件和空文件夹,非空文件夹不能使用delete方法删除
        //System.out.println(filea.delete());
        //System.out.println(file1.delete());

        //在f:\\a\\a.txt路径下创建b.txt
        createNewFileAt(file1, "b.txt");
        createNewFileAt(fileb, "b.txt");
        createNewFileAt(fileb, "c.txt");

        System.out.println("file1是否是文件:"+file1.isFile());//判断一个File对象是否是文件
        System.out.println("fileb是否是文件夹:"+fileb.isDirectory());//判断一个File对象是否是文件夹
       //获取文件夹中所有子文件夹和文件的名称(字符串形式)
        String[] files = fileb.list();
        System.out.println(files.length);
        for (String filestr0 : files) {
            System.out.print(filestr0+"\t");
        }

        //获取文件夹中所有子文件夹和文件的抽象路径(File对象)
        File[] files2 = fileb.listFiles();
        for (File file : files2) {
            System.out.println(file);
        }

        File file4 = new File("f:\\aa\\bb\\cc\\aa.txt");
        //在创建一个文件时,需要判断父目录是否存在,若不存在则创建父目录
        File parent = file4.getParentFile();
        if(!parent.exists())
            System.out.println("父目录不存在则创建:"+parent.mkdirs());//创建新的空文件夹
        System.out.println("创建文件aa.txt:"+file4.createNewFile());

        //对文件重命名
        File file = new File("f:\\a\\a.txt");
        file.createNewFile();
         //将原文件更改为f:\a\b.txt,其中路径是必要的。注意
         System.out.println(file.renameTo(new File("f:\\a\\b.txt")));

        method1("f:\\b\\c");
        method2("f:\\b\\c");
        method3("F:\\eclipse-workspace\\practice\\src");
    }
    //在某个文件的相同目录下创建出一个新文件
    public static void createNewFileAt(File file,String filename) {
        //获取父路径
        String parentPath = file.getParent();
        //创建file对象
        File file2  = new File(parentPath,filename);
        //创建文件
        try {
            file2.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //列出指定目录下所有子文件夹和文件
    public static void method1(String path) {
        File file = new File(path);
        //list()方法获得子文件夹和文件的字符串名称
        String[] arr = file.list();
        for (String st : arr) {
            System.out.print(st+"\t");
        }
    }
    //列出指定目录下的所有子文件夹和子文件,抽象路径
    public static void method2(String path) {
        File file = new File(path);
        //listFiles()获取指定路径下所有file对象
        File[] files =file.listFiles();
        for (File f : files) {
            if(f.isDirectory()) {
                System.out.println("子文件夹:");
                System.out.print(f.getName()+"\t");
            }else if (f.isFile()) {
                System.out.println("子文件:");
                System.out.print(f.getName()+"\t");
            }

        }
    }
    //列出指定目录下所欲后缀为.java文件
    public static void method3(String path) {
        File file = new File(path);
        String[] strFile = file.list();
        for (String s : strFile) {
            if(s.endsWith(".java"))
                System.out.println(s);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值