1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class PathTest
{
public static void main(String[] args)
{
File file = new File(".\\src\\baidu")
System.out.println(file.getAbsolutePath())
try
{
System.out.println(file.getCanonicalPath())
} catch (IOException e)
{
e.printStackTrace()
}
}
}
getAbsolutePath()和getCanonicalPath()的不同之处在于,getCanonicalPath()得到的是一个规范的路径,而getAbsolutePath()是用构造File对象的路径+当前工作目录。例如在上面的例子中.(点号)代表当前目录。getCanonicalPath()就会把它解析为当前目录但是getAbsolutePath()会把它解析成为目录名字(目录名字是点号)。
下面是上面程序在我电脑上的输出:
G:\xhuoj\konw\.\src\baiduG:\xhuoj\konw\src\baidu
其读取方法为:
import java.io.Fileimport java.io.FileNotFoundException
import java.io.IOException
import java.util.ArrayList
public class readFile {
private static ArrayList<String> listname = new ArrayList<String>()
public static void main(String[] args)throws Exception{
readAllFile("C:/Users/HP/Desktop")
System.out.println(listname.size())
}
public static void readAllFile(String filepath) {
File file= new File(filepath)
if(!file.isDirectory()){
listname.add(file.getName())
}else if(file.isDirectory()){
System.out.println("文件")
String[] filelist=file.list()
for(int i = 0i<filelist.lengthi++){
File readfile = new File(filepath)
if (!readfile.isDirectory()) {
listname.add(readfile.getName())
} else if (readfile.isDirectory()) {
readAllFile(filepath + "\\" + filelist[i])//递归
}
}
}
for(int i = 0i<listname.size()i++){
System.out.println(listname.get(i))
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)