Java-通过BufferedReader读取文件

Java-通过BufferedReader读取文件

Tags: Java

摘要

Java-通过BufferedReader读取文件

BufferedReader读取文件

在java中有多种方法读取文件,这里推荐使用最简单也是用的最多的方法 BufferedReader

package cn.javacore.io.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class _05_BufferedReaderExample1 {

    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new FileReader("/home/zhu/testing.txt"));
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

优化异常捕捉

上面的代码,try catch是不是看着太繁杂了?
如果升级到jdk1.7可以使用try-with-resources自动关闭引用的资源。

package cn.javacore.io.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class _05_BufferedReaderExample2 {

    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("/home/zhu/testing.txt"))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果是用的maven构建的项目,需要在pom.xml中指定jdk版本

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>java-io-study</groupId>
    <artifactId>java-io-study</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>java-io-study</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

代码下载

https://coding.net/u/javacore/p/java-io-study/git