在我的API(Spring启动)中,我有一个端点,用户可以一次上传多个文件.端点将列表作为输入MultipartFile.
我希望不直接将此MultipartFile对象直接传递给服务,因此我遍历每个对象MultipartFile并创建一个存储文件名及其的简单映射InputStream.
像这样:
for (MultipartFile file : files) {
try (InputStream is = multipartFile.getInputStream()) {
filesMap.put(file.getOriginalFilename(), is);
}
}
service.uploadFiles(filesMap)
Run Code Online (Sandbox Code Playgroud)
我对Java流和流关闭的理解非常有限.我认为一旦代码到达try块的末尾try-with-resources就会自动关闭InputStream.
在上面的代码中什么时候完全multipartFile.getInputStream()关闭?
我将流存储在地图中的事实会导致内存泄漏吗?
我在我的代码中使用try-with-resource块,想知道是否需要在方法结束时关闭资源或不需要?
try (S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
BufferedReader br = new BufferedReader(new InputStreamReader(object.getObjectContent()));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))){
String line;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
}
Run Code Online (Sandbox Code Playgroud) 使用 spring 控制器,端点在主体响应中返回文件。我想确保不要使用“尝试使用资源”来避免资源泄漏,但在邮递员中我会收到错误:
“错误”:“内部服务器错误”,“消息”:“流已关闭”,
Spring控制器中的代码片段:
InputStreamResource result;
ResponseEntity<Resource> response;
try(FileInputStream ios = new FileInputStream(file)){
result = new InputStreamResource(ios);
response = ResponseEntity.ok()
.headers(/*some headers here*/)
.contentLength(file.length())
.contentType(/*some media type here*/)
.body(result);
logger.info("successfully created");
return response;
} catch (IOException e) {
//some code here..
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,在日志中我收到了成功消息,但在邮递员或浏览器中(这是一个 GET 请求)我收到了错误。
如果不使用“try-with-resource”,它会起作用,但我担心这种方式会导致资源泄漏。
从 Java 9 开始,我们可以在 try-with-resources 中有效地使用最终变量。
下面的示例展示了一种资源初始化引发异常的情况。
public static void main(String[] args) {
Resource1 r1 = new Resource1();
Resource2 r2 = new Resource2(); // exception will be thrown
try (r1; r2) {
System.out.println("TryWithResources.main() try");
} catch (Exception e) {
System.out.println("TryWithResources.main() catch");
}
}
static class Resource1 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("TryWithResources.Resource1.close()");
}
}
static class Resource2 implements AutoCloseable {
public Resource2() {
throw new RuntimeException();
}
@Override
public void close() throws Exception {
System.out.println("TryWithResources.Resource2.close()"); …Run Code Online (Sandbox Code Playgroud) 我用来Files.walk()从目录中获取一些文件,但我从 Sonarqube 和 Sonarlint 代码分析中收到有关阻止程序错误的警告
连接、流、文件和其他实现 Closeable 接口或其超级接口 AutoCloseable 的类在使用后需要关闭。此外,该关闭调用必须在finally 块中进行,否则异常可能会导致调用无法进行。最好,当类实现 AutoCloseable 时,应使用“try-with-resources”模式创建资源并将自动关闭。
这是代码:
Files.walk(Paths.get(ifRecordsPath))
.filter(Files::isDirectory)
.map(ifRecordsCollector)
.map(ifRecordStreamAccumulator)
.forEach(ifRecordCollection::addAll);
return ifRecordCollection;
Run Code Online (Sandbox Code Playgroud)
我读了这篇文章,几乎遇到了问题,但我不知道如何准确地将流停止在正确的位置。当我添加finally块时,它仍然给出相同的错误
try {
Files.walk(Paths.get(ifRecordsPath))
.filter(Files::isDirectory)
.map(ifRecordsCollector)
.map(ifRecordStreamAccumulator)
.forEach(ifRecordCollection::addAll);
} finally {
Files.walk(Paths.get(ifRecordsPath)).close();
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
java spring try-catch-finally try-with-resources java-stream
我正在寻找 Pythonwith语句的 Java 等效项,并且我阅读了有关实现AutoCloseable接口以及对资源使用 try 的内容。
在Python中,上下文管理器(with语句)使用两种方法:__enter__和__exit__,但在Java中,try with resources块仅使用close,这相当于__exit__。
该方法是否有等效__enter__方法,以便在进入 try with resources 块时自动执行某个方法,而不仅仅是在该块结束时?
I\xe2\x80\x99m 是 Java 库的作者,该库提供对我们公司销售的 C++ 库的 Java 访问。类 \xe2\x80\x9cown\xe2\x80\x9d C++ 对象之一的实例,具有以下意义:该类具有一些long由某些方法设置的私有字段native,并且具有指向C++ 堆。由于 C++ 堆不会被垃圾回收,因此当拥有的 Java 对象不再需要它们时,特别是当拥有的 Java 对象本身不再需要时,必须手动释放内存,因此该类实现AutoClosable并close()释放实例拥有的所有 C++ 内存。理想情况下,用户将try在该类的实例上使用 -with-resources。
一位客户抱怨 SonarQube 警告他们, \xe2\x80\x99t 不会调用释放资源,并建议在对象上close()使用-with-resources,但该对象由变量或等效对象保存,并且一直存在,直到应用程序关闭(如据我了解)。我想帮助他们,但删除(按照他们的建议)根本就是\xe2\x80\x99不正确。问题与内存有关:当应用程序结束并且 C++ 库被卸载时,内存资源无论如何都会被释放(由操作系统)。trystaticAutoClosable
那么,理想情况下,如何AutoClosable以 SonarQube 检测到的方式关闭静态变量所持有的对象呢?Java 似乎没有可以使用的与类初始值设定项相反的类型。
我不\xe2\x80\x99t 有权访问SonarQube 来玩玩并看看什么可以工作,即当SonarQube 识别出close()将被调用时。我\xe2\x80\x99m 想要告诉他们应该适当地重新配置SonarQube 或抑制警告。问这个问题,我想确保它\xe2\x80\x99本质上是最好的行动方案。\xe2\x80\x9c是的,如果这是真的,\xe2\x80\x9d 将是一个合适的答案。当然,不使用全局状态,即没有 astatic AutoClosable是理所当然的,但我想他们已经知道了。
似乎没有人遇到过static AutoClosable对象的问题,因为 Stack Overflow 上没有关于它的问题。\n我认为这与.NET (C#) 中AutoClosable的类似,并且我发现这个问题非常询问这个问题,但是答案特定于用例和 .NET,并且 …
我昨天问了这个问题.我想我得到了正确的答案,但其中一个答案给我留下了一个问题.如果我有这样的代码:
File file = new File("somefile.txt");
try (Scanner in = new Scanner(file)) {
//do something but don't explicitly call file.close()
}
Run Code Online (Sandbox Code Playgroud)
这是错的吗?根据我的理解,如果资源实现了Closeable或AutoCloseable,那么try-with-resources语句将关闭资源.在我看来,我将其等同于使用with语句在Python中打开文件资源.但是@David Newcomb的答案说Scanner不是可以关闭的.
我查看了Java源代码,我发现了这一行:
public final class Scanner implements Iterator<String>, Closeable {
Run Code Online (Sandbox Code Playgroud)
这对我来说意味着我使用try-with-resources是安全的,并且文件资源将在try块的末尾关闭而不显式调用file.close().我是对的还是我应该采取不同的做法?
嗨有人可以分解并解释我下面的代码片段的含义是什么?例如在这里尝试做什么等
try (JsonWriter jsonwriter = Json.createWriter(strwriter)) {
jsonwriter.write(json);
}
Run Code Online (Sandbox Code Playgroud) 我想编写一个简单的服务器来侦听端口并生成新线程来处理新连接.我试图使用try-with-resources来接受新连接但是失败了,因为子线程中的套接字似乎立即关闭,我不明白为什么.
这是2个简化的例子.
a)服务器的工作示例(没有try-with-resources):
package MyTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServerA implements Runnable {
private int port;
private ServerSocket serverSocket;
public MyServerA(Integer port) {
this.port = port;
}
@Override
public void run() {
try {
serverSocket = new ServerSocket(port);
} catch(IOException ioe) {
System.err.println("error opening socket. " + ioe.getStackTrace());
}
while (true) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket); …Run Code Online (Sandbox Code Playgroud) java ×10
inputstream ×1
java-9 ×1
java-ee ×1
java-stream ×1
memory-leaks ×1
sockets ×1
sonarqube ×1
spring ×1
static ×1
stream ×1