In Java file.list() and file.listFiles() are used to list all File objects (file and directory) at given directory (All Files just one level down to that abstract file path). Suppose we want to list all nested files present at all level with respect to given abstract path.
Consider following E:\\Dir1\\file1.txt , E:\\Dir1\\Dir3\\file3.txt, E:\\Dir1\\file4.txt, E:\\Dir1\\file2.xml , E:\\Dir1\\temp.log - We want to list all files at E:\\Dir1. Output should be : file1.txt, file2.xml, file3.txt, file4.txt.
Below sample program display all files present below the given abstract path:-
======Sample Output========
E:\input\doc\Install_doc.doc
E:\input\EmployeeDST.xml
E:\input\extra\customerLog.json
E:\input\install_doc.pdf
E:\input\trailLog.json
========================
In above program, listAllFiles(File, List) method does looping on the given abstract path "E:\\input" and check if File object is Directory then again call this method again and if it is a file then add it to the list. Once this loop ends, list with all File object is returned and absolute path of each file is displayed.
Consider following E:\\Dir1\\file1.txt , E:\\Dir1\\Dir3\\file3.txt, E:\\Dir1\\file4.txt, E:\\Dir1\\file2.xml , E:\\Dir1\\temp.log - We want to list all files at E:\\Dir1. Output should be : file1.txt, file2.xml, file3.txt, file4.txt.
Below sample program display all files present below the given abstract path:-
package com.devinline.javaio; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; public class DisplayAllNestedFiles { public static void main(String[] args) { List<File> fileList = new LinkedList<>(); File dir = new File("E:\\input"); fileList = listAllFiles(dir, fileList); // Display all files with absolute paths for (File file : fileList) { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } } } // Recursive call to find File object is file or directory private static List<File> listAllFiles(File dir, List<File> fileList) { for (File fileEntry : dir.listFiles()) { if (fileEntry.isDirectory()) { listAllFiles(fileEntry, fileList); } else { fileList.add(fileEntry); } } return fileList; } }
E:\input\doc\Install_doc.doc
E:\input\EmployeeDST.xml
E:\input\extra\customerLog.json
E:\input\install_doc.pdf
E:\input\trailLog.json
========================
In above program, listAllFiles(File, List) method does looping on the given abstract path "E:\\input" and check if File object is Directory then again call this method again and if it is a file then add it to the list. Once this loop ends, list with all File object is returned and absolute path of each file is displayed.
Tags:
Java Input Output
Aivivu chuyên vé máy bay, tham khảo
ReplyDeletevé máy bay đi Mỹ
giá vé quy nhơn
vé máy bay quy nhơn đi tp hcm
vé máy bay từ sài gòn đi hà nội
đăng ký về việt nam ở mỹ
dịch vụ taxi đi sân bay nội bài
combo khách sạn vinpearl nha trang