本文最后更新于:2024年3月18日 凌晨
Java 文件与目录管理
获得文件的信息或进行文件的复制,删除,重命名等操作,需要使用File类的方法。
创建File对象
File(String path):path指定文件路径及文件名,它可以是绝对路径,也可以是相对路径,绝对路径的格式为"盘符:目录路径/文件名”,相对路径是指程序运行的当前盘,当前目录路径,例如:
1 File myFIle = new File("ect/motd" );
File(String path,String name):两个参数分别提供路径和文件名,例如:
1 myFile = new File("/etc" ,"motd" );
File(File dir,String name):利用已存在的File对象的路径定义新文件的路径,第2个参数为文件名。
1 File myFile = new File("/ect/motd" ,"new filename" );
注意 :不同平台下路径分隔符可能不一样,如果应用程序要考虑跨平台的情形,可以使用System.dirSep这个静态属性来给出分隔符。
获取文件或目录属性
借助File对象,可以获取文件和相关目录的属性信息,以下为常用的方法。
String getName():返回文件名。
String getPath():返回文件或目录路径。
String getAbsolutePath():返回绝对路径。
String getParent():获取文件所在目录的父目录。
boolean exists():文件是否存在。
boolean canWrite():文件是否可写。
boolean canWrite():文件是否可写。
boolean isFile():是否为一个正确定义的文件。
boolean isDirectory():是否为目录。
long lastModified():求文件的最后修改日期。
long length():求文件长度。
文件或目录操作
借助File对象,可实现对文件和目录的增,删,改,查,以下为常用方法。
boolean mkdir():创建当前目录的子目录。
String[] list():列出目录中的文件。
File[] listFiles():得到目录下的文件列表。
boolean renameTo(File newFile):将文件改名为新文件名。
boolean delete():删除文件。
boolean equals(File f):比较两个文件或目录是否相等。
[例113-7] :显示若干文件的基本信息,文件名通过命令行参数提供。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class 显示文件的信息 { public static void main (String[] args) { for (int i =0 ;i<args.length;i++) info(new File(args[i])); } public static void info (File f) { System.out.println("Name:" +f.getName()); System.out.println("Path:" +f.getPath()); System.out.println("Absolute Path:" +f.getAbsolutePath()); if (f.exists()){ System.out.println("File is Readable:" +f.canRead()); System.out.println("File is Writeable:" +f.canWrite()); System.out.println("File is " +f.length()+"bytes" ); }else { System.out.println("File does not exist" ); } } } Name:显示文件的信息.java Path:src/Study/流式输入输出与文件处理/文件与目录管理/显示文件的信息.java Absolute Path:/Users/lucian/Documents/Code/Java/src/Study/流式输入输出与文件处理/文件与目录管理/显示文件的信息.java File is Readable:true File is Writeable:true File is 809bytes
文件的随机访问
一般的文件访问均是顺序访问,对同一文件操作只限于读操作或者写数据,不能同时进行,而且只能按记录顺序逐个读或逐个写。
RandomAccessFile类提供了对流进行随机读写的能力,该类实现了DataInput和DataOutput接口,因此,可使用两接口中定义的所有方法实现数据的读写操作,为支持流的随机读写访问,该类该添加定哦以来如下方法。
long getFilePointer():返回当前指针。
void seek(long pos):将文件指针定位到一个绝对地址,地址是相对于文件头的偏移量,地址0表示文件的开头。
long length():返回文件的长度。
setLength(long new Length):设置文件的长度,在删除记录时可以采用,如果文件的长度大于设定值,则按设定值设定新长度,删除文件多余部分,如果文件长度小于设定值,则对文扩展,扩充部分内容不定。
RamdomAccessFile类的构造方法如下:
public RandomAccessFile(String name,String mode)
public RandomAccessFile(File file,String mode)
其中,第1个参数指定要打开的文件,第2个参数决定了访问文件的权限,其值可以为‘r’或‘rw’,‘r’表示只读,‘rw’表示可进行读和写两种访问,创建RandomAccessFile对象时,如果文件不存在,则打开文件,如果不存在将创建一个文件。
[例13-8] :应用系统用户访问统计。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class 应用系统用户访问统计 { public static void main (String[] args) { long count; try { RandomAccessFile fio; fio = new RandomAccessFile("src/Study/流式输入输出与文件处理/文件的随机访问/count.txt" , "rw" ); if (fio.length() == 0 ) count = 1L ; else { fio.seek(0 ); count = fio.readLong(); count = count + 1L ; System.out.println(count); } fio.seek(0 ); fio.writeLong(count); fio.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } } }
说明 :利用随机文件存储访问计数值,将计数值写入文件的开始位置,注意,进行读写操作前要关注文件指针的定位。
Files & Paths
从Java 7开始,提供了Files和Paths这两个工具类,能极大地方便我们读写文件。
虽然Files和Paths是java.nio包里面的类,但封装了很多读写文件的简单方法,例如,我们要把一个文件的全部内容读取为一个byte[],可以这么写:
1 byte [] data = Files.readAllBytes(Paths.get("/path/to/file.txt" ));
如果是文本文件,可以把一个文件的全部内容读取为String:
1 2 3 4 5 6 String content1 = Files.readString(Paths.get("/path/to/file.txt" )); String content2 = Files.readString(Paths.get("/path/to/file.txt" ), StandardCharsets.ISO_8859_1); List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt" ));
1 2 3 4 5 6 7 8 byte [] data = ... Files.write(Paths.get("/path/to/file.txt" ), data); Files.writeString(Paths.get("/path/to/file.txt" ), "文本内容..." , StandardCharsets.ISO_8859_1); List<String> lines = ... Files.write(Paths.get("/path/to/file.txt" ), lines);
此外,Files工具类还有copy(),delete(),exists(),move()等快捷方法操作文件和目录。
注意 :Files提供的读写方法,受内存限制,只能读写小文件,例如配置文件等,不可一次读入几个G的大文件,读写大型文件仍然要使用文件流,每次只读写一部分文件内容。