Hướng dẫn php try-with-resources - tài nguyên dùng thử php
Câu lệnh try-with-resources là câu lệnh Ví dụ dưới đây đọc dòng đầu tiên từ một tập tin. Nó sử dụng một thể hiện của static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); }} Trong ví dụ trên, tài nguyên được khai báo trong Trước Java SE 7, bạn có thể sử dụng khối
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); }} Tuy nhiên, trong ví dụ trên, nếu các phương thức Bạn có thể khai báo một hoặc nhiều tài nguyên trong câu lệnh public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException { java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII; java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Mở file zip và tạo đầu ra với // câu lệnh try-with-resources try ( java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) ) { // Liệt kê từng mục for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Lấy tên đầu vào và ghi nó tới tập tin đầu ra String newLine = System.getProperty("line.separator"); String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); } }}try ( Trong ví dụ trên, câu lệnh Ví dụ sau đây sử dụng câu lệnh public static void viewTable(Connection con) throws SQLException { String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query);try (Statement stmt = con.createStatement()) { while (rs.next()) { String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); } } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); }} Tài nguyên Lưu ý: Mỗi câu lệnh Ngoại lệ bị bỏ quaMột ngoại lệ có thể được ném ra từ khối mã lệnh kết hợp với câu lệnh Các lớp thực thi giao diện AutoCloseable hoặc CloseableXem các giao diện Javadoc gồm |