标签: try-with-resources

如果从 try-with-resource 返回 InputStream 是安全的

它是安全的,从一试,与资源的语句返回一个输入流来处理流的结束,一旦调用者已经消耗了呢?

public static InputStream example() throws IOException {
    ...
    try (InputStream is = ...) {
        return is;
    }
}
Run Code Online (Sandbox Code Playgroud)

java return inputstream try-with-resources

1
推荐指数
1
解决办法
3471
查看次数

为什么在使用try-with-resources时在try()中声明Resource

try-with-resources语句 以下是来自Java Docs的示例

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

按照文档,

try-with-resources语句确保在语句结束时关闭每个资源.

我的问题是,为什么我需要在try关键字后立即在括号内声明资源.(比如上面的BuffereReader)

BuffereReader实现 java.lang.AutoCloseable

那么为什么不支持这样的事情,

static String readFirstLineFromFile(String path) throws IOException {
        try{
            BufferedReader br =
                       new BufferedReader(new FileReader(path))
            return br.readLine();
        }
    }
Run Code Online (Sandbox Code Playgroud)

并且只是在尝试之后隐式关闭资源对象.(因为它实现了AutoCloseable)

我只是想了一下,为什么要改变语法.

请正确阅读问题,仅关于语法.

java exception-handling exception java-7 try-with-resources

1
推荐指数
1
解决办法
2260
查看次数

如何使用Java 6解决CSVReader的尝试资源错误

我被迫用JDK 6构建JAR文件,因为它将用在公司的便携式计算机上,并且便携式计算机的所有者如果不经过IT人员的便携式计算机就无法更新其Java版本。

因此,如何解决此方法的try-with-resources错误:

public static String importFile(String filepath){
    String insertQuery = "INSERT INTO SALESMAN VALUES (?,?)";
    String status;

    try (CSVReader reader = new CSVReader(new FileReader(filepath), ','); //error here
        Connection connection = DBConnection.getConnection();){
        Statement stmt = connection.createStatement();

        PreparedStatement pstmt = connection.prepareStatement(insertQuery);
        String[] rowData = null;

        int i = 0;
        while((rowData = reader.readNext()) != null){
            for (String data : rowData){
                pstmt.setString((i % 2) + 1, data);
                if (++i % 2 == 0)
                    pstmt.addBatch();
                if (i % 20 == 0)
                    pstmt.executeBatch();
            }
        } …
Run Code Online (Sandbox Code Playgroud)

java java-6 opencsv try-with-resources

1
推荐指数
1
解决办法
986
查看次数

使用Try with Resources进行Java Post连接

我想使用try with resources实现处理POST请求的代码.

以下是我的代码:

public static String sendPostRequestDummy(String url, String queryString) {
    log.info("Sending 'POST' request to URL : " + url);
    log.info("Data : " + queryString);
    BufferedReader in = null;
    HttpURLConnection con = null;
    StringBuilder response = new StringBuilder();
    try{
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();
        // add request header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("Content-Type", "application/json");
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(queryString);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        log.info("Response Code : …
Run Code Online (Sandbox Code Playgroud)

java exception-handling try-catch try-with-resources

0
推荐指数
1
解决办法
4667
查看次数

try-with-resources fails but try works

I'm trying to set up a service which listens to a RabbitMQ server and I've set up code using the RabbitMQ Sample code from Github, which includes the following try-with-resources block

try (Connection connection = factory.newConnection();
     Channel channel = connection.createChannel()) {
        // code here
}
Run Code Online (Sandbox Code Playgroud)

When I use the same code and build and run this service using java -cp myJar.jar MyService, it just starts and ends immediately (and echo $? returns 0)

However, if I replace the …

java try-catch rabbitmq try-with-resources java-11

0
推荐指数
1
解决办法
57
查看次数

Maven构建错误 - -source 1.5不支持try-with-resources

这是来自Maven项目的简单代码,该项目具有try-with-resources.我使用eclipse作为我的IDE.

public class Hello {

    public static void main(String[] args) {

        try(FileInputStream fi = new FileInputStream("ANC")){

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用clean package -U它构建它时,会给我以下错误.

Hello.java:[11,20] try-with-resources is not supported in -source 1.5
  (use -source 7 or higher to enable try-with-resources). 
Run Code Online (Sandbox Code Playgroud)

但是,我将我的java编译器设置为Java 1.8并且在Jave Build路径中JRE系统库也是JDK 1.8.此错误仍然存​​在.

这是我的POM文件(减去junit依赖)

<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>com.commonutil</groupId>
  <artifactId>PropertyFile</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>PropertyFile</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>
Run Code Online (Sandbox Code Playgroud)

注意:在pom.xml中设置目标和源也没有帮助.对此有任何帮助表示赞赏.谢谢.

java eclipse maven try-with-resources

-1
推荐指数
1
解决办法
794
查看次数