读取文件:test.txt

java按行解析文件 java 按行读取文件内容_java


代码:

1.按行读取文本文件的内容并输出

public class test3 {
    //按行读取文本文件的内容
    public static void readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String readStr;
            while ((readStr = reader.readLine()) != null) {
                System.out.println(readStr);
            }
            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        readFileContent("F:\\test.txt");
    }
}

运行结果:

java按行解析文件 java 按行读取文件内容_System_02


2.按行读取文本文件的内容并储存到列表中

public class test3 {
    //按行读取文本文件的内容并储存到列表中
    public static List readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        List list = new ArrayList();
        try {
            reader = new BufferedReader(new FileReader(file));
            String readStr;
            while ((readStr = reader.readLine()) != null) {
                list.add(readStr);
            }
            reader.close();
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List list = readFileContent("F:\\test.txt");
        System.out.println(list);
    }
}

运行结果:

java按行解析文件 java 按行读取文件内容_java_03