Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách khai báo nhiều resource trong try-with-resources Java 9?

Câu lệnh Try-with-resources cải tiến trong Java 9. Nếu đã có resource là final hoặc tương đương final variable, có thể dùng variable đó trong try-with-resources mà không cần khai báo biến mới trong try-with-resources.

Có thể khai báo nhiều resource trong block try. Khối khởi tạo try có thể có bất kỳ số lượng resource nào cho kết quả null hoặc non-null.

Ví dụ dưới khai báo nhiều resource trong try-with-resources statement.

Ví dụ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class MultipleResourcesTest {
    public static void main(String args[]) throws IOException {
        System.out.println(readData("test"));
    }

    static String readData(String message) throws IOException {
        try (Reader inputString = new StringReader(message);
             BufferedReader br = new BufferedReader(inputString)) {
            return br.readLine();
        }
    }
}

Kết quả

test