# File類別和listFiles(),list(),walk(),find()比較
:::warning
### File 代表的是一個路徑,指向目標檔案或資料夾位置
File path = new File("."); 表示當前目錄。
File path = new File("C:\\Java"); 絕對路徑的檔案或資料夾位置。
File path = new File(new File("."),"bin"); 表示當前目錄的bin資料夾,如果找不到bin資料夾就會丟出NullPointerException
:::
:::info
### listFiles()方法的返回型別
該路徑當前目錄下所有檔案或資料夾的絕對路徑(pathname,注意File型別指的是路徑,而不是檔案)
:::
# Files.walk 取得指定目錄下的所有資料夾和檔案
**Question:**
```java=
public static void main(String[] args) throws IOException{
Stream<Path> files = Files.walk(Paths.get(System.getProperty("user.home"))); //Files.walk 取得這個路徑底下所有目錄的資料夾和檔案
files.forEach(fName -> { //line n1
try {
Path aPath = fName.toAbsolutePath(); //line n2
System.out.println(fName + ":"
+ Files.readAttributes(aPath, BasicFileAttributes.class).creationTime());
} catch (IOException ex) {
ex.printStackTrace();
}
});
}
```
## What is the result?
**A. All files and directories under the home directory are listed along with their attributes.**
B. A compilation error occurs at line n1.
C. The files in the home directory are listed along with their attributes.
D. A compilation error occurs at line n2.
- [x] **Answer: A**
- [參考網站](https://coderbee.net/index.php/java/20131030/543)
:::info
Files新增了3个方法用於走訪目錄:
- Files.list(Path)
- Files.walk(Path, int, FileVisitOption...)
- Files.walk(Path, FileVisitOption...)
---
Files.list方法只走訪當前目錄的資料夾和檔案,
Files.walk方法走訪指定目錄下的所有資料夾和檔案(深度優先走訪),除非指定了最大深度。
walk方法的int用來指定走訪的最大深度。
:::
---
# Files.find 在指定目錄下,加了匹配器的走訪方法
- **原始方法**
```java=
Stream<Path> matches = Files.find(start, maxDepth, matcher, options);
```
- **範例1**
```java=
Stream<Path> matches = Files.find(inputDir, Integer.MAX_VALUE, (path, attr) -> inputFile.equals(path), FileVisitOption.FOLLOW_LINKS)
```
- **範例2**
```Java=
Stream<Path> stream = Files.find(Paths.get ("/company"), 1,(p,b) -> b.isDirectory (), FileVisitOption.FOLLOW_LINKS);
```
**Question:**
目錄
/company/emp/info.txt
/company/emp/benefits/b1.txt
```java=
//line n1
stream.forEach(s->System.out.print(s));
```
### Which code fragment can be inserted at line n1to enable the code to print only /company/emp?
A. Stream<Path> stream = Files.list (Paths.get ("/company"));
**B. Stream<Path> stream = Files.find(Paths.get ("/company"), 1,(p,b) -> b.isDirectory (),FileVisitOption.FOLLOW_LINKS);**
C. Stream<Path> stream = Files.walk (Paths.get ("/company"));
D. Stream<Path> stream = Files.list (Paths.get ("/company/emp"));
- [x] **Answer: B**
:::info
選項A: 取得company當前目錄下的所有檔案
選項B: 取得company當前目錄的檔案往下一層的資料夾路徑
選項C: 走訪所有在company底下的所有目錄的檔案
選項D: 取得company/emp 當前目錄的所有檔案
:::
###### tags: `ocpjp`