File
java.io.File类:文件和目录路径名的抽象表示形式
通过File对象可以访问文件的属性。
通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)。
File属性
separator:系统文件路径分隔符
public static final String separator = “” + separatorChar;
separatorChar:
public static final char separatorChar = fs.getSeparator();
pathSeparator:
public static final String pathSeparator = “” + pathSeparatorChar;
pathSeparatorChar:
public static final char pathSeparatorChar = fs.getPathSeparator();
File构造函数
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}
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);
}
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);
}
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);
}
File常用方法
canRead()
canWrite()
canExecute()
exists()
isDirectory()
isFile()
isHidden()
lastModified()
length()
getName()
getPath() 如果是绝对路径,返回绝对路径,否则返回相对路径
getAbsolutePath() 返回绝对路径
getParent() 返回上一级目录,如果是相对,返回null
通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)
createNewFile()
delete()
mkdir() 创建目录,父目录必须存在,否则失败
mkdirs() 创建目录,父目录不存在一同创建
作业:
通过File获取指定路径下的文件夹及其子文件和文件夹。