一、遍历目录下的文件(不包括子目录下文件)
public static void main(String[] args) {
String inputPath = "F:\\log\\test";
File file = new File(inputPath); //获取其file对象
File[] fs = file.listFiles(); //遍历path下的文件和目录,放在File数组中
for(File f:fs){ //遍历File[]数组
String fileName = f.getName(); //获取文件和目录名
if (!f.isDirectory()) { //另外可用fileName.endsWith("txt")来过滤出以txt结尾的文件
logger.info("isFile:"+f); //打印文件全路径
logger.info("isFile:"+fileName); //打印文件名
}
}
}
打印结果如下:
二、遍历目录下的所有文件(包括子目录下文件)
private static void func(File file) {
File[] fs = file.listFiles();
for (File f : fs) {
if (f.isDirectory()) //若是目录,则递归打印该目录下的文件
func(f);
if (f.isFile()) //若是文件,直接打印
System.out.println(f);
}
}
public static void main(String[] args) {
String inputPath = "F:\\log\\test";; //要遍历的路径
File file = new File(inputPath); //获取其file对象
func(file);
}
打印结果如下:
三、一行一行的遍历文件内容
private static void parseFile(File file) {
BufferedReader reader = null;
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK");
reader = new BufferedReader(isr);
String line;
// 一次读入一行,直到读入null为文件结束
int i=0;
while ((line = reader.readLine()) != null) {
System.out.println(i+"---"+line);
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}