java讀取文件夾下文件及txt內容


public class PositionController {
    // 讀取txt內容
    public static String txt2String(File file) {
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));// 構造一個BufferedReader類來讀取文件
            String s = null;
            while ((s = br.readLine()) != null) {// 使用readLine方法,一次讀一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    // 讀取文件夾下所有文件名
    public static List getFile(File file) {
        List listLocal = new ArrayList<>();
        if (file != null) {
            File[] f = file.listFiles();
            if (f != null) {
                for (int i = 0; i < f.length; i++) {
                    getFile(f[i]);
                    listLocal.add(f[i]);
                }
            } else {
                // System.out.println(file);
            }
        }
        return listLocal;
    }

    public String getTxt(ModelMap map) throws FileNotFoundException {
            // 文件夾下每一個txt名
            String path = "D:/wode/TestReallyData/txt2/txt_all/";
            File all = new File(path);
            //將全部txt存到list中
            List allPath = getFile(all);
             // 讀取txt內容 並轉換成List
             for(int i = 0 ;i <allPath.size();i++){
                File file = new File(i);
                String content = txt2String(file);
             }
      }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM