java获取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 void main(String[] args) {
        File file = new File("C:\\Users\\Administrator\\Desktop\\文件名.txt");
        String s = txt2String(file);
        String[] split = s.split("\\r?\\n");
        for (String s1 : split) {
            if (s1.length() > 0) {
                String[] split1 = s1.split("\\s+");
                for (String s2 : split1) {
                    if (s2.length() > 0) {
                        System.out.println(s2);
                    }
                }
            }

        }
    }

内容出现乱码,则先把文件设置为UTF-8格式。

猜你喜欢

转载自blog.csdn.net/qq_39648029/article/details/104016261