package write_read;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
public class ReadFile {
public ReadFile() {
}
/**
* 读取某个文件夹下的所有文件
*/
public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
try {
File file = new File(filepath);
if (!file.isDirectory()) {
//如果是文件
System.out.println("文件绝对路径=" + file.getAbsolutePath());
} else if (file.isDirectory()) {
//如果是文件夹(及目录);
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("文件绝对路径="
+ readfile.getAbsolutePath());
} else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return true;
}
public static void main(String[] args) {
try {
readfile("E:/getimgs");
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
System.out.println("目录读取成功");
}
}
输出结果如下:
文件绝对路径=E:\getimgs\1\1\2.jpg
文件绝对路径=E:\getimgs\1\2\2.jpg
文件绝对路径=E:\getimgs\1\2.jpg
文件绝对路径=E:\getimgs\2\1\2.jpg
文件绝对路径=E:\getimgs\2\2\2.jpg
文件绝对路径=E:\getimgs\2\2.jpg
文件绝对路径=E:\getimgs\2.jpg
目录读取成功
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
public class ReadFile {
public ReadFile() {
}
/**
* 读取某个文件夹下的所有文件
*/
public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
try {
File file = new File(filepath);
if (!file.isDirectory()) {
//如果是文件
System.out.println("文件绝对路径=" + file.getAbsolutePath());
} else if (file.isDirectory()) {
//如果是文件夹(及目录);
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("文件绝对路径="
+ readfile.getAbsolutePath());
} else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return true;
}
public static void main(String[] args) {
try {
readfile("E:/getimgs");
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
System.out.println("目录读取成功");
}
}
输出结果如下:
文件绝对路径=E:\getimgs\1\1\2.jpg
文件绝对路径=E:\getimgs\1\2\2.jpg
文件绝对路径=E:\getimgs\1\2.jpg
文件绝对路径=E:\getimgs\2\1\2.jpg
文件绝对路径=E:\getimgs\2\2\2.jpg
文件绝对路径=E:\getimgs\2\2.jpg
文件绝对路径=E:\getimgs\2.jpg
目录读取成功