java.io.File类代表系统文件名(路径和文件名)。
常见的构造方法:public File(String pathname),public File(String parent,String child)
File的静态属性:String separator(路径分隔符lunix,windows皆可用)
File对象可以访问文件的属性:
canRead(),canWrite(),exists(),isDirectory(),isFile(),isHidden(),lastModified()
length(),getName(),getPath()
File对像创建空文件或目录(两者皆不存在时)
createNewFile(),delete(),mkdir(),makdirs
例:
import java.io.*;
public class TestFile{
public static void main(String args []){
String separator = File.separator;
String filename = "myfile.txt";
String directory = "mydir1"+separator+"mydir2";
File f = new File(directory,filename);
if(f.exists()){
System.out.println("文件名:"+f.getAbsolutePath());
System.out.println("文件大小:"+f.length());
}else{
f.getParentFile().mkdirs();
try{
f.createNewFile();
}catch(IOException e){
e.printStackTrance();
}
}
}
}
例:批量更改文件扩展名
import java.io.*;
public class BatchRenameFiles{
public static void main(String args []){
recurse(new File(args[0]),"-----+");
}
private static void recurse(File dirfile,String regex){
String [] contents = dirfile.list();
for(int i = 0; i < contents.length;i++){
File childfile = new File(dirfile,contents[i]);
if(childfile.isFile()){
System.out.println(indent+contents[i]);
System.out.println(indent+getFileType(contents[i]));
String filename = childfile.getAbsolutePath();
if(getFileType(contents[i].equals(“java”))){
if(filename.lanstIndexOf(".") >= 0)
filename = filename.substring(0,filename.lastIndexOf("."));
childfile.renameTo(new File(filename+".txt"));
}
}else{
System.out.println(indent+contents[i]+" : ");
recurse(childfile, indent+"--+ ");
}
}
}
public static String getFileType(String fileUri){
File file = new File(fileUri);
String fileName = file.getName();
String fileType = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()) ;
return fileType;
}
}
例:递归列出目录下的所有文件及目录
import java.io.*;
public class FileList{
public static void main(String args []){
File f = new File("d:/A");
System.out.println(f.getName());
tree(f,1);
}
public static void tree(File f,int level){
String preStr = "";
for(int i = 0;i < level;i ++){
preStr += "------";
}
File[] childs = f.listFiles();
for(int i = 0;i < childs.length;i++){
System.out.println(preStr+childs[i].getName());
if(childs[i].isDirectory()){
tree(childs[i],level+1);
}
}
}
}