如果在f:\aa文件夹中,有如下图的文件夹与文件:

那么,在Java中,则如此读取f:/aa下的所有文件路径:
1、首先由于用到了文件与容器类下的ArrayList,所以在开头要引入如下包:
- import java.io.*;
- import java.util.*;
获取项目工程路径:this.getServletContext().getRealPath("/");
因为文件是在部署到服务器中所以需要获取绝对路径
2、方法如下,其中File dirFile除了盘符,比如f:,以外,能够接受一切合法的路径。由于盘符下含有一些系统文件,拒绝访问,因为读取盘符,可能会出现空指针异常。
-
-
- public static ArrayList<String> Dir(File dirFile) throws Exception {
- ArrayList<String> dirStrArr = new ArrayList<String>();
-
- if (dirFile.exists()) {
-
- File files[] = dirFile.listFiles();
- for (File file : files) {
-
- if (dirFile.getPath().endsWith(File.separator)) {
- dirStrArr.add(dirFile.getPath() + file.getName());
- } else {
-
- dirStrArr.add(dirFile.getPath() + File.separator
- + file.getName());
- }
- }
- }
- return dirStrArr;
- }
其上的方法,是不读取f:\aa下的新建文件夹下的xlsx,如果在读取的过程中,遇到文件夹要同时读取其包含所有子文件夹、文件时,则要用到递归,先设置一个全局的动态数组:
- public static ArrayList<String> dirAllStrArr = new ArrayList<String>();
然后方法如下:
- public static void DirAll(File dirFile) throws Exception {
-
- if (dirFile.exists()) {
- File files[] = dirFile.listFiles();
- for (File file : files) {
-
- if (file.isDirectory()) {
-
- DirAll(file);
- } else {
-
- if (dirFile.getPath().endsWith(File.separator)) {
- dirAllStrArr.add(dirFile.getPath() + file.getName());
- } else {
- dirAllStrArr.add(dirFile.getPath() + File.separator
- + file.getName());
- }
- }
- }
- }
- }
其实在读取的过程中,关键是利用listFiles()方法,获取本文件夹下的所有文件列表,之后和《【Java】移动文件夹及其所有子文件与子文件夹》(点击打开链接),《【Java】利用文件输入输出流完成把一个文件夹内的所有文件拷贝的另一的文件夹的操作》(点击打开链接)一样,遇到文件夹则进行递归。
上面整个方法的来起来是这样的一个java文件:
- import java.io.*;
- import java.util.*;
-
- public class fileList {
-
-
- public static ArrayList<String> dirAllStrArr = new ArrayList<String>();
-
-
-
- public static ArrayList<String> Dir(File dirFile) throws Exception {
- ArrayList<String> dirStrArr = new ArrayList<String>();
-
- if (dirFile.exists()) {
-
- File files[] = dirFile.listFiles();
- for (File file : files) {
-
- if (dirFile.getPath().endsWith(File.separator)) {
- dirStrArr.add(dirFile.getPath() + file.getName());
- } else {
-
- dirStrArr.add(dirFile.getPath() + File.separator
- + file.getName());
- }
- }
- }
- return dirStrArr;
- }
-
- public static void DirAll(File dirFile) throws Exception {
-
- if (dirFile.exists()) {
- File files[] = dirFile.listFiles();
- for (File file : files) {
-
- if (file.isDirectory()) {
-
- DirAll(file);
- } else {
-
- if (dirFile.getPath().endsWith(File.separator)) {
- dirAllStrArr.add(dirFile.getPath() + file.getName());
- } else {
- dirAllStrArr.add(dirFile.getPath() + File.separator
- + file.getName());
- }
- }
- }
- }
- }
-
- public static void main(String[] args) throws Exception {
- File dirFile = new File("f:/aa");
- System.out.println(Dir(dirFile));
- DirAll(dirFile);
- System.out.println(dirAllStrArr);
- }
- }
运行结果如下:
