欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

6.1(java学习笔记)File类

程序员文章站 2022-04-24 20:00:10
1.路径分隔符,文件分隔符。 路径分隔符(“;”) 文件名称分隔符(“\”windows,“/”Linux等)。 不同平台使用的文件分隔符是不一样的,所以File类中提供了分隔符常量,它会根据平台的不同自行选择对应的分隔符。 这样便于跨平台,假如我们写死的话,就具有一定的局限性。 路径分割符:Fil ......

1.路径分隔符,文件分隔符。

路径分隔符(“;”)

文件名称分隔符(“\”windows,“/”linux等)。

不同平台使用的文件分隔符是不一样的,所以file类中提供了分隔符常量,它会根据平台的不同自行选择对应的分隔符。

这样便于跨平台,假如我们写死的话,就具有一定的局限性。

 

路径分割符:file.pathseparator

文件名称分割符:file.separator

 

import java.io.file;

public class test {
    public static void main(string[] args) {
        system.out.println(file.pathseparator);//路径分隔符
        system.out.println(file.separator);//文件名称分隔符
    }
}
运行结果:
;
\     //由于这是在windows平台上,所有打印出来的是“\”,如果是linux上打印的就是“/”

 

import java.io.file;

public class test {
    public static void main(string[] args) {
        system.out.println(file.pathseparator);
        system.out.println(file.separator);
        string path1 = "e:\\test\\a.txt";//路径表示方法1,
        string path2 = "e:" + file.separator + "test" + file.separator +"a.txt";//路径表示方法2
        system.out.println(path1);
        system.out.println(path2);
    }
}
运行结果:
;
\
e:\test\a.txt
e:\test\a.txt

上列代码中的路径表示方法1,方法2都可以用于表示路径,但是建议使用第二种,无论是从动态的更改路径,还是从跨平台角度考虑,第二组都要好一些。

 

2.file构造方法

创建一个文件实例用于对该文件进行操作。构造参数是被操作文件的路路径。

简单的说就是和需要进行操作的文件之间建立一个联系,而这个联系的关键就是文件的路径。

 

file(string parent, string child)

file(file parent, string child)

file(string pathname)

 

string getpath()

将抽象路径名转换为路径字符串

string getabsolutepath()

将抽象路径名转换为绝对路径字符串

import java.io.file;

public class test {
    public static void main(string[] args) {
    //    system.out.println(file.pathseparator); // ';'
    //    system.out.println(file.separator);     // '\'
        string parent = "e:" + file.separator;
        string childtesttxt = "test.txt";
        string childtestword = "text.docx";
        file f1 = new file(parent,childtesttxt);//文件路径parent + chidetesttxt,绝对路径创建
        file f2 = new file(new file(parent),childtestword);//文件路径parent+childtestdoc,绝对路径创建
        file f3 = new file(parent+"text.xls");//绝对路径创建
        system.out.println(f1.getpath());//获取路径地址
        system.out.println(f2.getpath());
        system.out.println(f3.getpath());
    }
}
运行结果:
e:\test.txt
e:\text.docx
e:\text.xls

 

就像上列代码中parent是e:\,后面添加的child都是相对于parent而言的,就是说child在parent后面。

建立路径简单的说就是parent+child。

 

我们来看下面这样一个例子

import java.io.file;

public class test {
    public static void main(string[] args) {
        string parent = "ft";
        string child ="t.txt";
        file f1 = new file(parent,child);
        file f2 = new file(new file(parent),child);
        file f3 = new file("ft\\t.txt");
        system.out.println(f1.getpath());
        system.out.println(f1.getabsolutepath());
        system.out.println(f2.getpath());
        system.out.println(f2.getabsolutepath());
        system.out.println(f3.getpath());
        system.out.println(f3.getabsolutepath());
    }
}
运行结果:
ft\t.txt                 //getpaht()
e:\eclipse\io\ft\t.txt   //getabsolutepaht()
ft\t.txt
e:\eclipse\io\ft\t.txt
ft\t.txt
e:\eclipse\io\ft\t.txt

没有加盘符创建的就是相对路径,这个相对路径是相对于我们目前这个工程保存的位置而言的。

我这里的工程是e:\eclipse\io\,相对路径前面会自动加上当前工程地址(e:\eclipse\io\),然后才是我们输入的的地址(ft\t.txt)。

相对地址,绝对地址的区别就是加不加盘符的区别。我们也可以发现使用getpath获取相对路径时获取的不是完整的绝对地址。

使用getpath()获取只会获取传递进去那部分路径的地址,传递进去的是绝对路径返回的就是绝对路径,传递进去的是相对地址就返回相对路径,

不会加上相对路径前面一部分的地址。而要获取绝对地址则需要用getabsolutepath().

 

3.file常用方法

3.1string getname()  //获取文件名

import java.io.file;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t.txt";
        file f1 = new file(parent,child);
        file f3 = new file("ft\\t.txt");
        system.out.println(f1.getname());
        system.out.println(f3.getname());
    }
}
运行结果:
t.txt
t.txt

 

3.2 string getparent()//返回上一级目录,相对返回null

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t.txt";
        file f1 = new file(parent,child);
        file f3 = new file("t.txt");
        system.out.println(f1.getabsolutepath());
        system.out.println(f1.getparent());
        system.out.println(f3.getabsolutepath());
        system.out.println(f3.getparent());
    }
}
运行结果:
e:\t.txt
e:\
e:\eclipse\io\t.txt
null

 

3.2

import java.io.file;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t.txt";
        file f1 = new file(parent,child);
     //   file f3 = new file("t.txt");
        system.out.println(f1.getabsolutepath());
        system.out.println(f1.exists());//判断文件(t.txt)是否存在,存在返回true,反之false
        
    }
}
运行结果:
e:\t.txt false

 

3.3

boolean canread()
boolean canwrite()

判断文件,文件夹是否可读、可写。

import java.io.file;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t.txt";
        file f1 = new file(parent,child);
        file f3 = new file("e:\\");
        system.out.println(f1.getabsolutepath());
        system.out.println("文件是否存在:"+f1.exists());
        system.out.println("文件是否可写:"+f1.canwrite());
        system.out.println(f3.getabsolutepath());
        system.out.println("文件是否存在:"+f3.exists());
        system.out.println("文件是否可写:"+f3.canwrite()); 
    }
}
运行结果:
e:\t.txt
文件是否存在:false
文件是否可写:false
e:\
文件是否存在:true
文件是否可写:true

上列代码中t.txt文件并不存在只是构建了路径,但文件本身不存在,文件不存在的话自然不可读。

如果文件存在,也要考虑其是否可读、可写。因为可能有些文件进行了读写权限的设置。

 

3.4

boolean isfile()//判断是否是文件,是文件返回true反之返回false。若文件不存在返回false。
boolean isdirectory()//判断是否是文件夹,是文件夹返回true反之返回false。若文件夹不存在返回false。

import java.io.file;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t";
        file f1 = new file(parent,child);
        file f2 = new file(parent,"t.txt");
        file f3 = new file("e:\\ssm\\pom.xml");
        system.out.println(f1.getabsolutepath());
        system.out.println("文件是否存在:"+f1.exists());
        system.out.println("是不是文件?"+f1.isfile());
        system.out.println("是不是文件夹?"+f1.isdirectory());
        system.out.println(f2.getabsolutepath());
        system.out.println("文件是否存在:"+f2.exists());
        system.out.println("是不是文件?"+f2.isfile());
        system.out.println("是不是文件夹?"+f2.isdirectory());
        system.out.println(f3.getabsolutepath());
        system.out.println("文件是否存在:"+f3.exists());
        system.out.println("是不是文件?"+f3.isfile());
        system.out.println("是不是文件夹?"+f1.isdirectory());
    }
}
e:\t                 //创建的一个文件夹实例,但实际的路径是不存在的
文件是否存在:false
是不是文件?false
是不是文件夹?false
e:\t.txt            //创建一个文件实例,但实际的路径是不存在的
文件是否存在:false
是不是文件?false
是不是文件夹?false
e:\ssm\pom.xml      //创建一个文件实例,该路径存在。
文件是否存在:true
是不是文件?true
是不是文件夹?false

上列代码e:\t,e:\t.txt都不存在,e:\ssm\pom.xml存在,

可以看出如果构造的文件就不会被作为文件,同样构造的文件夹不存在也不会作为文件夹。

 

3.5

boolean isabsolute();//判断是否为绝对路径

import java.io.file;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t";
        file f1 = new file(parent,child);
        file f2 = new file("t.txt");
        
        system.out.println(f1.getpath());
        system.out.println(f1.isabsolute());
        system.out.println(f2.getpath());
        system.out.println(f2.isabsolute());
    }
}
运行结果:
e:\t
true
t.txt
false

 

3.6

long length()//返回文件的字节数

import java.io.file;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="ssm";
        file f1 = new file(parent,child);
        file f2 = new file("e:\\ssm\\pom.xml");
        
        system.out.println(f1.getpath());
        system.out.println(f1.length());
        system.out.println(f2.getpath());
        system.out.println(f2.length());
    }
}
运行结果:
e:\ssm
4096
e:\ssm\pom.xml
4644

6.1(java学习笔记)File类  6.1(java学习笔记)File类

 

可以看到文件的字节数正常读取了,而文件夹读取的确是有问题的,这是因为length只能读取文件,读取文件夹的数值并不准确。

如果文件夹不存在或为空文件夹可能读取的字节数是0,这个可以自行实验。

 

3.7

boolean createnewfile()/如果文件不存在且创建成功返回true,文件已存在返回false

import java.io.file;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t.txt";
        file f1 = new file(parent,child);      //该文件不存在
        file f2 = new file("e:\\ssm\\pom.xml");//该文件已存在
        
        try {
            system.out.println(f1.createnewfile());
            system.out.println(f2.createnewfile());
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }
}
运行结果;
true
false

6.1(java学习笔记)File类

可以看到e盘多了一个我们指定创建的文件。

 

3.8

boolean delete()//删除文件或文件夹,

import java.io.file;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="t.txt";
        file f1 = new file(parent,child);
        file f2 = new file("e:\\ssm\\pom.xml");
        f1.delete();
    }
}
运行结果:
true

这样就将我们之前创建的t.txt删除了。

 

3.9

public static file createtempfile(string prefix, string suffix, file directory)

//prefix前缀,suffix后缀,directory创建文件所在文件夹.suffix可以为null,此时将使用.tmp。

如果需要文件自动删除,需配合deleteonexit()方法。该方法为静态方法,可通过类名调用,

调用完会返回一个file对象,对临时文件进行操作。

void deleteonexit()//虚拟机终止时,删除该文件。

 

import java.io.file;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="";
        file f1 = new file(parent,child);
        try {
            file temp = file.createtempfile("temp",".txt",f1);
            thread.sleep(5000);
            temp.deleteonexit();
        } catch (ioexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        } catch (interruptedexception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }
}

程序运行后会在e盘下创建一个已temp开头,后缀为.txt的文件。

5s后程序自动删除。注意这里删除文件是在程序运行结束后才删除,

例如我们在temp.deleteonexit();后面加上thread.sleep(50000);

会发现过了五十秒后文件才会自动删除。

 

3.10

boolean mkdir()//创建文件夹,所有上一级目录必须存在
boolean mkdirs()//创建文件夹,如果上一级目录不存在,则自动创建

 

import java.io.file;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="parent\\child";//e盘下parent文件夹不存在
        file f1 = new file(parent,child);//e:\parent目录下创建child文件夹
        system.out.println(f1.mkdir());
        system.out.println(f1.mkdirs());
    }
}

运行结果:
false true

使用mkdir创建文件夹时,最后一级目录之前的目录必须全部存在,否则就会创建失败。

而mkdirs创建时,如果有目录不存在就会直接创建。

 

3.11

string[] list()//返回一个字符串数组该抽象路径名所表示的目录中的文件和目录,
由这个抽象路径名表示的目录中的文件和目录的字符串数组。如果目录为空,则数组将为空。
如果此抽象路径名不表示目录,或发生i/o错误,则返回null。


file[] listfiles()
返回一个抽象路径名数组,表示由该抽象路径名表示的目录中的文件。

如果此抽象路径名不表示目录,则此方法返回null。否则返回一个文件对象数组,一个目录中的每个文件或目录。

import java.io.file;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="java";
        file f1 = new file(parent,child);
        string[] fstring = f1.list();
        file[] ffile = f1.listfiles();
        for(string temp:fstring){
            system.out.println(temp);
        }
        system.out.println("------------------------------------");
        for(file temp:ffile){
            system.out.println(temp.getabsolutepath());
        }
    }
}
bin
copyright
db
include
javafx-src.zip
jre
lib
license
readme.html
release
src.zip
thirdpartylicensereadme-javafx.txt
thirdpartylicensereadme.txt
------------------------------------
e:\java\bin
e:\java\copyright
e:\java\db
e:\java\include
e:\java\javafx-src.zip
e:\java\jre
e:\java\lib
e:\java\license
e:\java\readme.html
e:\java\release
e:\java\src.zip
e:\java\thirdpartylicensereadme-javafx.txt
e:\java\thirdpartylicensereadme.txt

我们要首先要注意调用list和listfiles方法的抽象路径是文件夹,

其次list返回的是该文件夹下所有文件夹和文件的名称,是以字符数组的形式返回的。

而listfiles返回的是该文件夹下所有文件夹和文件的抽象路径对象,拥有这个对象我们可以对这些文件夹及文件进行操作。

 

利用listfiles我们就可以打印出指定文件夹下所有文件了。

import java.io.file;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="java";
        file f1 = new file(parent,child);
        string[] fstring = f1.list();
        file[] ffile = f1.listfiles();//获取指定目录下所有文件及目录的抽象路径对象
        printallfilename(ffile);
    }
    public static void printallfilename(file[] filearray){//打印所有文件名
        for(file temp:filearray){
            if(temp.isdirectory()){//如果当前对象为文件夹,则继续获取该文件夹下所有对象。
                file[] ffile = temp.listfiles();
                printallfilename(ffile);//递归
            }
            system.out.println(temp.getabsolutepath());//输出所有对象的绝对地址
        }
    }
}
运行结果://文件很多只截取了一部分。
e:\java\lib\missioncontrol\features\org.eclipse.equinox.p2.rcp.feature_1.2.0.v20140523-0116\epl-v10.html . . . e:\java\thirdpartylicensereadme-javafx.txt e:\java\thirdpartylicensereadme.txt

 

3.12

file[] listfiles(filefilter filter)//返回一个抽象路径名数组,该数组中的元素必须满足文件过滤器的筛选条件。

 我们来看下过滤器是如何起作用的,我们先来看下listfiles(filefilter filter)的源码

6.1(java学习笔记)File类

主要看if(filter == null || filater.accept(f))这一句,accept是filefilter接口中的方法,

是用于指导筛选条件的,满足条件返回ture反之返回false。我们接着看后面

满足筛选条件就会返回true,则该文件对象会被加入到一个文件对象数组中,

最后会返回这个文件数组对。

可见指定accept方法中的条件才是关键。

我们接着来看下accept方法的定义。

6.1(java学习笔记)File类

传递进去的是一个文件的地址名,也可以理解为是一个文件对象,

在该方法中对pathname文件对象指定规则返回true,则该文件就通过了筛选,反之亦然。

我们接下里看一个实际的例子,例如我要输出某一个文件夹下所有后缀为.xml的文件。

import java.io.file;
import java.io.filefilter;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="java";
        file f1 = new file(parent,child);
        string[] fstring = f1.list();
        file[] ffile = f1.listfiles(new filefilter(){
            @override
            public boolean accept(file pathname) {
                // todo auto-generated method stub
                return pathname.isdirectory() || pathname.getname().endswith(".xml");
            }    
        });
        printallfilename(ffile);
    }
    public static void printallfilename(file[] filearray){
        if(filearray == null)
            return;
        for(file temp:filearray){
            if(temp.isdirectory()){
                file[] ffile = temp.listfiles(new filefilter(){//由于filefilter是接口,所以需要构造匿名内部类。
                    @override                                  //这里也可以定义一个类实现filefileter接口,然后new一个对象
                    public boolean accept(file pathname) {
                        // todo auto-generated method stub
                        return pathname.isdirectory() || pathname.getname().endswith(".xml");
                    }//指定规则,当前文件是以.xml结尾或者是文件夹则通过筛选。虽然文件夹不用输出,但是后续需要通过文件夹去寻找下一级中是否有.xml文件。
                    
                });
                printallfilename(ffile);
            }
            if(!temp.isdirectory())//当前对象为文件夹则不输出。
                system.out.println(temp.getabsolutepath());
        }
    }
}
运行结果:
略

 

3.12

public static file[] listroots()//返回所有根目录对象

import java.io.file;
import java.io.filefilter;
import java.io.ioexception;

public class test {
    public static void main(string[] args) {
        string parent = "e:\\";
        string child ="java";
        file f1 = new file(parent,child);
        string[] fstring = f1.list();
        file[] ffile = f1.listroots();//获取根目录文件对象
        for(file temp:ffile){
            system.out.println(temp.getabsolutepath());
        }
    //    printallfilename(ffile);
    }
    public static void printallfilename(file[] filearray){
        if(filearray == null)
            return;
        for(file temp:filearray){
            if(temp.isdirectory()){
                file[] ffile = temp.listfiles(new outxmlfile());
                printallfilename(ffile);
            }
            if(!temp.isdirectory())
                system.out.println(temp.getabsolutepath());
        }
    }
}

class outxmlfile implements filefilter{//创建类实现接口方法添加过滤器
    public boolean accept(file pathname) {
        // todo auto-generated method stub
        return pathname.isdirectory() || pathname.getname().endswith(".xml");
    }
}
运行结果;
c:\
d:\
e:\
f:\

这里的根目录是指最顶端的根目录。