通過Java中的path對象流來訪問目錄內容,主要通過Java.nio.file.DirectoryStream來實現,System.getProperty("user.dir")是獲取當前文件的路徑具體代碼如下:
import java.nio.file.*;
import java.io.*;
public class TryPath {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自動生成方法存根
Path currentPath=Paths.get("E:/WorkingProject/123");
//獲取當前的文件所在的文件路徑
System.out.println(currentPath);
DirectoryStream<Path> paths=null;
//提取目錄文件的流
try{
paths=Files.newDirectoryStream(currentPath);
//依次輸出文件目錄
for(Path path:paths)
{
System.out.println(path.getFileName());//獲取文件名
}
}catch(NotDirectoryException e){
System.err.println(currentPath +" is not a directory."+e);
}catch(IOException e){
System.err.println(" I/O error."+e);
}
}
}
實現結果如下: