String separator = File.separator;
String path =
“dir1″+separator+”dir2″;
String filename = “Test.txt”;
File file = new
File(path,filename);
if (file.exists())
{
System.out.println(“文件保存的路径:”+file.getAbsolutePath());
System.out.println(“文件的大小:”+file.length());
}else
{
file.getParentFile().mkdirs();//创建除了文件之外的所有目录,由于创建两个以上所以mkdirs加了“S”
try
{
file.createNewFile();
} catch (IOException e) {
// TODO
Auto-generated catch
block
e.printStackTrace();
}
}
1、文件名的操作
public String
getName();返回文件对象名字符串,串空时返回null
public String toString();返回文件名字符串
public
String getParent();返回文件对象父路径字符串,不存在时返回null
public File
getPath();转换相对路径名字符串
public String getAbsolutePath();返回绝对路径名字符串,如果为空返回当前使用目录,也可以使用系统指定目录
public String
getCanonicalPath()throws IOException;返回规范的路径名串
public File
getCanonicalFile()throws IOException;返回文件(含相对路径名)规范形式
public File
getAbsoluteFile();返回相对路径的绝对路径名字符串
public boolean renameTo(File
dest);重命名指定的文件
public static Fiel createTempFile(String prifix,String
suffix,File directory)throws IOException;在指定目录建立指定前后缀空文件
public static Fiel
createTempFile(String prifix,String suffix)throws
IOException;在指定目录建立指定前后缀文件
public boolean createNewFile()throws
IOException;当指定文件不存在时,建立一个空文件
2、文件属性测试
public boolean
canRead();测试应用程序是否能读指定的文件
public boolean
canWrite();测试应用程序是否能修改指定的文件
public boolean exists();测试指定的文件是否存在
public
boolean isDirectory();测试指定文件是否是目录
public boolean
isAbsolute();测试路径名是否为绝对路径
public boolean isFile();测试指定的是否是一般文件
public
boolean isHidden();测试只的是否是隐藏文件
3、一般文件信息和工具
public long
lastModified();返回只的文件最后被修改的时间
public long length();返回指定文件的字节长度
public
boolean delete();删除指定的文件
public void
deleteOnExit();当虚拟机执行结束时请求删除指定的文件或目录
4、目录操作
public boolean
mkdir();创建指定的目录,正常建立时返回true,否则返回false
public boolean
mkdirs();常见指定的目录,包含任何不存在的父目录
public String[]list();返回指定目录下的文件(存入数组)
public
String[]list(FilenameFilter filter);返回指定目录下满足指定文件过滤器的文件
public
File[]listFiels();返回指定目录下的文件
public File[]listFiles(FilenameFilter
filter);返回指定目录下满足指定文件过滤器的文件
public File[]listFiles(FileFilter
filter);返回指定目录下满足指定文件过滤器的文件(返回路径名应满足文件过滤器)
public static
File[]listRoots();列出可用文件系统的根目录结构
5、文件属性设置
public boolean
setLastModified(long time);设置指定文件或目录的最后修改时间,操作成功返回true,否则返回false
public
boolean setReadOnly();标记指定的文件或目录为只读属性,操作成功返回true,否则返回false
6、其他
public URL
toURL()throws MalformedURLException;把相对路径名存入URL文件
public int compareTo(OBject
o);与另一个对性比较名字
public boolean equals(Object obj);与另一个对象比较对象名
public int
hashCode();返回文件名的哈希码