欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java读取文件夹下的所有文件

程序员文章站 2022-04-15 17:54:20
package test;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;//Read all files under the folderpublic class ReadFolder {public static void main(String[] ....
package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
//Read all files under the folder
public class ReadFolder {
	public static void main(String[] args) {
		BufferedReader bufReader = null;
		try {
			
			String filepath = "E:\\test\\corpus";
			File file = new File(filepath);
			if (!file.isDirectory()) {
				System.out.println("Not folder");
			} else if (file.isDirectory()) {
				System.out.println("Be folder");
				
				String str;
				int lineNo;
				
				String[] filelist = file.list();
				
				for (int i = 0; i < filelist.length; i++) {
					File readfile = new File(filepath + "\\" + filelist[i]);
					String absolutePath = readfile.getAbsolutePath();
					String fileName = readfile.getName();
					
					//Read each file
					bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(absolutePath)));
					lineNo=0;
					
					while((str=bufReader.readLine())!=null) {
						++lineNo;
						if(str.endsWith("*END*")) {
							System.out.println(fileName+"(*END*)-->"+lineNo);
						}
						
						if("".equals(str)) {
							System.out.println(fileName+"(空行)-->"+lineNo);
						}
					}
					
				}
				System.out.println("All finished");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bufReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
		}

	}
}

 

本文地址:https://blog.csdn.net/Scanner_sc/article/details/109570987

相关标签: java