打開文件讀取第一行spa
static String firstLineOffFile(String path) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(path)); try { return reader.readLine(); } finally { reader.close(); } }
存在不足調試
使用這個構造資源,必須先實現AutoCloseable接口,其中包括單個返回void的close()方法。Java類庫與第三方庫中的許多類和接口,如今都實現或擴展了AutoCloseable接口。好比BufferReader的類繼承關係code
public class BufferedReader extends Reader {
}
public abstract class Reader implements Readable, Closeable {
}
public interface Closeable extends AutoCloseable {
}
一開始的例子改造爲
static String firstLineOffFile2(String path) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(path))){ return reader.readLine(); } }
優勢blog