标签: try-with-resources

此语言级别不支持try-with-resources - Android

在以下发布的代码中我在android中"在这个语言级别不支持尝试使用资源"的问题,我试图将语言设置为7但是它仍然不断给我相同的示例加上它一直给我选项改为语言7.

public String ReadFile(String fileName) {

    try (BufferedReader br = new BufferedReader(new FileReader(fileName+".txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }

        String everything = sb.toString();
        return everything;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(SaveNLoadRank.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SaveNLoadRank.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "1";
}
Run Code Online (Sandbox Code Playgroud)

android notsupportedexception try-with-resources

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

使用try-with-resources时需要flush()调用

会隐含地try-with-resources打个电话flush()吗?

如果是,请在以下代码段bw.flush()中安全删除?

static void printToFile1(String text, File file) {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
        bw.write(text);
        bw.flush();
    } catch (IOException ex) {
        // handle ex
    }
}
Run Code Online (Sandbox Code Playgroud)

PS.我在官方文件中没有看到任何关于它的描述:

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html https://docs.oracle.com/javase/8/docs/api/java/lang/Au​​toCloseable.html

java try-with-resources

20
推荐指数
3
解决办法
7189
查看次数

在Java中如何确保Closeable接口的close()方法的幂等性?

Closeable接口是在Java 5中引入的,而AutoCloseable接口是在Java 7中与try-with-resources语句一起引入的.Closeable扩展(自Java 7以来)Autocloseable接口.

OCA/OCP Java SE 7 - 程序员I和II学习指南中,它在第399页上说:

如果我们打close()多次电话会发生什么?这取决于.对于实现的类,实现AutoCloseable必须是幂等的.这意味着你可以close()整天打电话,第二次及以后什么都不会发生.[...]对于实施的课程,Closeable没有这样的保证.

所以根据这个文本,实现AutoCloseable需要是幂等的,而Closeable不是.现在,当我AutoCloseable在docs.oracle.com上查看界面文档,它说:

请注意,与close方法不同Closeable,此close方法不需要是幂等的.换句话说,close多次调用此方法可能会产生一些可见的副作用,Closeable.close如果多次调用则需要不起作用.

现在这与书中所写的相反.我有两个问题:

(1)什么是正确的?docs.oracle.com上的文档还是书?这两个接口中的哪一个需要幂等性?

(2)无论哪一个都需要是幂等的 - 我是否正确Java实际上根本没有办法确保它是幂等的?如果是这样,那么close方法的" 幂等"的"要求" 是程序员应该做的事情,但我永远不能确定使用该界面的人确实这样做了,对吧?在这种情况下,幂等仅仅是oracle的建议,对吗?

java oracle idempotent try-with-resources autocloseable

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

在调用超级构造函数时尝试使用资源

InputStream在构造函数中打开一个然后将其传递给超级构造函数时,有没有什么好的方法可以使用try-with-resources ?

基本上我想要做的是:

public class A {
    public A(InputStream stream) {
        // Do something with the stream but don't close it since we didn't open it
    }
}

public class B {
    public B(File file) {
        // We open the stream so we need to ensure it's properly closed
        try (FileInputStream stream = new FileInputStream(file)) {
            super(new FileInputStream(file));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当然,因为super必须是构造函数中的第一个语句,所以这是不允许的.有没有什么好办法实现这个目标?

java java-8 try-with-resources

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

在try-with-resources中声明的变量注释?

只是想知道哪些注释可以用于在try-with-resources语句中声明的变量,这是根据其语法允许的.语言规范(Java 7)的第14.20.3节内容如下:

TryWithResourcesStatement:
    tryResourceSpecification Block Catches opt最后选择

ResourceSpecification:
    (资源;选择 )

资源:
    资源;资源

资源:
    VariableModifiers opt类型VariableDeclaratorId =表达式

VariableModifiers扩展为(第14.4节),

VariableModifiers:
    VariableModifier
    VariableModifiers VariableModifier

VariableModifier:
    Annotation之一 final

你去:VariableModifier可以有注释.嗯,这基本上意味着,我们可以这样写:

try( @SomeAnnotation SomeType obj = createSomeType() ) { 
  //some code
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何以及什么样的注释可以用于资源尝试并实现什么样的行为?任何创新的想法?有人用过它们吗?

java annotations java-7 java-8 try-with-resources

20
推荐指数
2
解决办法
1001
查看次数

尝试使用资源文件编写器是一种好习惯吗

我在网上和“Effective Java”(Joshua Bloch 着)一书中看到了这个例子。

try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))){
  writer.write(str); // do something with the file we've opened
}
catch(IOException e){
  // handle the exception
}
Run Code Online (Sandbox Code Playgroud)

这个例子没有问题,BufferedWriter它会自动关闭,然后关闭FileWriter; 但是,在其他情况下,如果我们以这种方式声明 2 个嵌套资源:

try (AutoClosable res = new Impl2(new Impl1())) {... }
Run Code Online (Sandbox Code Playgroud)

我想可能会发生new Impl1()性能良好但new Impl2()崩溃的情况,在这种情况下,Java 将没有引用Impl1, 以关闭它。

像这样始终独立声明多个资源(即使在这种情况下不需要)难道不是更好的做法吗?

try(FileWriter fw = new FileWriter(fileName); 
    BufferedWriter writer = new BufferedWriter(fw)){ ... }
Run Code Online (Sandbox Code Playgroud)

java java-7 try-with-resources

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

java.util.concurrent.locks.Lock的AutoCloseable包装中的任何风险?

随着try-with-resourceJava 7的推出,我很惊讶地看到Lock它还没有被改造成一个AutoCloseable.它似乎相当简单,所以我自己添加如下:

class Lock implements AutoCloseable {
    private final java.util.concurrent.locks.Lock _lock;
    Lock(java.util.concurrent.locks.Lock lock) {
        _lock = lock;
        _lock.lock();
    }
    @Override 
    public void close() {
        _lock.unlock();
    }
}
Run Code Online (Sandbox Code Playgroud)

这适用于一个AutoCloseableReentrantReadWiteLock类,用法如下:

try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) {
    // do something
}        
Run Code Online (Sandbox Code Playgroud)

由于这似乎是直接和规范使用自动关闭RAII我认为必须有一个很好的理由这不应该做.有人知道吗?

java raii auto-close try-with-resources

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

Java中的RAII设计模式

来自C++背景,我是RAII模式的忠实粉丝.我已经广泛使用它来处理内存管理和锁管理以及其他用例.

使用Java 1.7,我看到我可以使用try-with-resources模式来创建RAII模式.

我使用RAII创建了一个示例应用程序并且它可以工作,但是我看到java中的编译器警告.

样品申请

try(MyResource myVar = new MyResource(..))
{
    //I am not using myVar here 
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

warning: [try] auto-closeable resource node is never referenced in body of corresponding try statement
Run Code Online (Sandbox Code Playgroud)

我理解警告,这意味着我应该在try块中使用变量,我不需要一直这样做.

看看这个我假设Java并没有真正支持RAII,我可能误用了仅用于资源管理的功能,而不是C++中的RAII等价物.

几个问题:

  1. 我的理解是否正确?
  2. 忽视这些警告有多大风险?
  3. 如何通过蚂蚁忽略这些警告?
  4. 我有一个简单的方法来克服这个问题吗?

for 4我正在考虑将构造函数调用拆分为更简单的构造函数和像这样的实例方法

try(MyResource myVar = new Resource())
{
   myvar.Initialize()
   ....

}
Run Code Online (Sandbox Code Playgroud)

这解决了编译器的问题,但从设计的RAII中获取了本质.

java raii try-with-resources

18
推荐指数
2
解决办法
3447
查看次数

Stream上的收集操作是否会关闭流和底层资源?

以下代码是否需要包含在try-with-resources中以确保底层文件已关闭?

List<String> rows = Files.lines(inputFilePath).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

java file-io java-8 try-with-resources java-stream

16
推荐指数
2
解决办法
2741
查看次数

与 (...) 的连接被泄露。您是否忘记关闭响应主体?

尽管我的代码看起来不错,但我不断收到警告消息。消息是:

WARNING: A connection to http://someurl.com was leaked. Did you forget to close a response body?
java.lang.Throwable: response.body().close()
    at okhttp3.internal.platform.Platform.getStackTraceForCloseable(Platform.java:148)
    at okhttp3.RealCall.captureCallStackTrace(RealCall.java:89)
    at okhttp3.RealCall.execute(RealCall.java:73)
    at com.example.HTTPSClientReferenceRate.runClient(HTTPSClientReferenceRate.java:78)
    at com.example.HTTPSClientReferenceRate.main(HTTPSClientReferenceRate.java:137)
Run Code Online (Sandbox Code Playgroud)

我正在使用 Java 8。我尝试过使用传统方法try-catch和这种方法 ( try-with-resources):

boolean repeatRequest = true;

while(repeatRequest) {
    Call call = client.newCall(request);
    try (Response response = call.execute()){
        if (!response.isSuccessful()) {
            log.error("Error with the response: " + response.message());
            continue;
        }
        ResponseBody body = response.body();
        if (body == null){
            log.error("Error when getting body from the response: " + …
Run Code Online (Sandbox Code Playgroud)

java try-with-resources

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