标签: try-with-resources

Sonar报告了try-with-resources块中分支覆盖不足的误报

使用SonarQube的最新版本(4.3.2),try-with-resources块会给catch线路的分支覆盖带来误报.例如:

public List<String> getLines(String filename) {
    try (InputStream inputStream = getInputStream(filename)){
        return IOUtils.readLines(inputStream);
    } catch (IOException e) { // <<<<<<< REPORTS AS BRANCH COVERAGE 2/8 
        throw new IllegalArgumentException(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我的单元测试涵盖了每个点抛出的异常,所有其他线路都有100%覆盖 - 实际覆盖率为100%.那里的"8"来自哪里?抛出异常不是8个地方.

我尝试添加// NOSONAR到问题行,甚至尝试将其添加到每一行,但报告是相同的.

其他类型的问题使用的时候忽略了// NOSONAR,所以它不是一个声纳配置问题.

我怀疑这是因为声纳不允许try-with-resources块产生的字节码中的额外try-catch块.

有没有办法装饰成功导致声纳忽略这种特殊误报的代码?

false-positive try-with-resources sonarqube

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

Java 使用 Clip 和 Try - with - 资源块,结果没有声音

我正在为我的学校项目重写我的 AudioManager 类,但遇到了一个问题。我的教授告诉我使用 Try-with-resources 块加载我的所有资源,而不是使用 try/catch(请参阅下面的代码)。我正在使用 javax.sound.sampled.Clip 中的 Clip 类,一切都与我的 PlaySound(String path) 方法完美配合,该方法使用 try/catch/ 如果我不 close() 剪辑。我知道如果我 close() 剪辑我不能再使用它。我已阅读 Oracle Docs for Clip 和 Try-with-resources,但找不到解决方案。所以我想知道的是:

是否可以使用 Try-with-resource 块在剪辑关闭之前播放/收听剪辑中的声音?

// Uses Try- with resources. This does not work.
public static void playSound(String path) {
try {
    URL url = AudioTestManager.class.getResource(path);
    try (Clip clip = AudioSystem.getClip()){
    AudioInputStream ais = AudioSystem.getAudioInputStream(url);
    clip.open(ais);
    clip.start();
    }
} catch( LineUnavailableException | UnsupportedAudioFileException  | IOException  e) {
    e.printStackTrace();}
}

// Does not use Try- with resources. This …
Run Code Online (Sandbox Code Playgroud)

java audio javasound clip try-with-resources

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

如何在if语句中使用Try-with-resources?

我有简单的代码:

try (FileReader file = new FileReader(messageFilePath);
     BufferedReader reader = new BufferedReader(file)) {

    String line;

    while ((line = reader.readLine()) != null) {
        ////
    }
} 
Run Code Online (Sandbox Code Playgroud)

我想写这样的东西:

FileReader file = null;
///.....

try(file = (file == null ? new FileReader(messageFilePath) : file);
     BufferedReader reader = new BufferedReader(file)) {

    String line;

    while ((line = reader.readLine()) != null) {
        ////
    }
} 
Run Code Online (Sandbox Code Playgroud)

它允许我重用FileReader.可能吗?如果没有,如何正确重用FileReader?我使用java 8,如果它很重要.

java resources java-7 try-with-resources

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

使用资源处理临时文件

对于我的应用程序,我必须编写一个方法,该方法接受一个InputStreamas参数,将内容写入临时文件,执行一些操作,最后删除临时文件.

这是我到目前为止:

public void myMethod(InputStream in, String name) {
    //...
    Path path = Paths.get("./tmp/benchmarks/" + name + ".zip")

    try {
        Files.copy(in, path);
        //operations...
    } catch (IOException e) {
        //error handling for copy...
    } finally {
        try {
            Files.delete(path));
       } catch (IOException e) {
           //error handling for delete...
       }
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

它完成了这项工作,但看起来也很丑陋.我想知道是否有一些方法可以try-with-resources更优雅地处理这个问题.有可能吗?

更新:我在十分钟内写了一个即时解决方案.它看起来像这样:

public class TemporaryFileHandler implements AutoCloseable {

    private File file;

    public TemporaryFileHandler(final InputStream in, final Path path) throws IOException {
        Files.copy(in, path);
        this.file …
Run Code Online (Sandbox Code Playgroud)

java java.nio.file try-with-resources

3
推荐指数
2
解决办法
5808
查看次数

如何使用Try-with-Resources两次使用PreparedStatement?

在常规Java Try-Catch块中使用PreparedStatements时,我可以更改PreparedStatement以在需要时运行不同的查询,如下所示:

String sqlStatement = "update someTable set someValue = true";
try{
    PreparedStatement pstmt = con.prepareStatement(sqlStatement);
    pstmt.executeUpdate();

    /* Here I change the query */
    String anotherSqlStatement = "update aDifferentTable set something = false";
    pstmt = con.prepareStatement(anotherSqlStatement);
    pstmt.executeUpdate();
}
catch(Exception ex){
    ...
}
Run Code Online (Sandbox Code Playgroud)

使用Java的Try-with-Resources执行此操作的正确方法是什么?这是我尝试过的,但是"无法分配try-with-resources语句的资源pstmt".

try(Connection con = DriverManager.getConnection(someConnection, user, password);
    PreparedStatement pstmt = con.prepareStatement(sqlStatement)){
    ResultSet rs = pstmt.executeQuery();
    ....

    /* Here I attempt to change the query, but it breaks */
    String anotherSqlStatement = "select something from someTable";
    pstmt = con.prepareStatement(anotherSqlStatement); …
Run Code Online (Sandbox Code Playgroud)

java try-catch prepared-statement try-with-resources

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

尝试资源总是会关闭资源

尝试使用资源总是关闭资源而不管错误情况如何?我的意思是考虑以下代码:

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

br永远关闭吗?我读过Oracle文档说:

无论try语句是正常还是突然完成,它都将被关闭

因此,无论程序是正常运行还是抛出异常,它都会起作用.但是条件如崩溃System.exit还是JVM崩溃呢?我知道这些条件不适用于finally阻止.那么尝试资源失败的条件是什么?

这只是我要求好奇心,有人可以对此有所了解吗?

java try-with-resources

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

尝试使用资源

我在"试用资源"主题中遇到了一个疑问.

程序代码:

public class Suppressed_Exception_Eg03 
{ 
    public static void main(String[] args)
    { 
        try (Wolf obj = new Wolf(); Deer obj1 = new Deer();)
        { 
            //Both close statements are executed . 
            //Therefore , we see two closing stmts 
        } 
        catch(Exception e) 
        { 
            System.out.println(e.getMessage()); 
        } 
} 

static class Wolf implements AutoCloseable 
{ 
    @Override 
    public void close() throws Exception 
    { 
        System.out.println("Closing Wolf !"); 
        throw new RuntimeException("In Wolf !"); 
    } 
} 

static class Deer implements AutoCloseable 
{ 
    @Override 
    public void close() throws Exception 
    { …
Run Code Online (Sandbox Code Playgroud)

java try-with-resources

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

try-with-resources中的catch是否涵盖了括号中的代码?

它是由不明的文件,如果catch下一个try-with-resources覆盖初始化部分与否.

换句话说,给定此代码片段:

    try (InputStream in = getSomeStream()) {
        System.out.println(in.read());
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
    }
Run Code Online (Sandbox Code Playgroud)

catch如果IOException被扔到里面我会被调用吗?getSomeStream()

或者catch仅覆盖花括号内的块,即 System.out.println(in.read())

java try-with-resources

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

Java使用带有try-with-resources的扫描仪

我有两个版本的Java代码,它们会在用户输入“ q”版本1之前获取用户输入:

public class Test {
    public static void main(String[] args) {
        String input = "";
        while (!input.equals("q")) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Input: ");
            input = scanner.nextLine();
            System.out.println("Input was: " + input);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

版本2:

public class Test {
    public static void main(String[] args) {
        String input = "";
        while (!input.equals("q")) {
            try(Scanner scanner = new Scanner(System.in)){
                System.out.print("Input: ");
                input = scanner.nextLine();
                System.out.println("Input was: " + input);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

版本1可以正常工作,但版本2不能正常工作。也就是说,第一次读取用户输入后,会产生错误

Input: 12
Input was: 12Exception …
Run Code Online (Sandbox Code Playgroud)

java try-catch try-with-resources

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

尝试使用资源为什么不能修改资源

我尝试将参考扫描的值设置为null时发现无法编译的try资源示例

try(Scanner scan = new Scanner(System.in)) {
    String s = scan.nextLine();
    System.out.println(s);
    scan = null;
}
Run Code Online (Sandbox Code Playgroud)

我问这个编译错误背后的规则是什么,我在网上做了一些搜索,但是没有找到解释它的规则。谢谢您的解释:=)

java try-catch variable-assignment java-8 try-with-resources

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