java - FileOutputStream 抛出 FileNotFoundException(打开的文件太多)
问题描述
我的应用程序以某种方式抛出“java.io.FileNotFoundException: /file/path (Too many open files)”,我不知道哪个部分导致了这个异常,因为 try-with-resources 应该在写入后关闭文件,但它不知何故没有。我没有其他正在写入文件的资源,因此它不是由外部应用程序引起的。
我还尝试替换流以及将方法 writeToFile(String filename, Double data) 更改为非静态,这就是 B 类现在在每个循环中为 DataFileWriter 创建一个新实例的原因。我希望这会以某种方式强制 FileOutputStream 关闭,但它没有帮助。
public class A {
public static void main(String[] args) {
List<Data> dataList = dao.getAll();
B classB = new B();
dataList.stream().forEach(data -> {
classB.someMethod(data);
});
}
}
public class B {
public void someMethod(Data data) {
// Some transformation happens here which results in transformedData
writeToFile(filename, transformedData);
}
private void writeToFile(String filename, Double[][] data) {
Arrays.stream(data).forEach(d -> {
DataFileWriter dataFileWriter = new DataFileWriter();
dataFileWriter.writeToFile(filename, d);
});
}
}
public class DataFileWriter {
public void writeToFile(String filename, Double data) {
File file = new File(filename);
if (!file.getParentFile().isDirectory()) file.getParentFile().mkdirs();
try (FileOutputStream fOut = new FileOutputStream(filename, true) {
byte b[] = data.getBytes();
fOut.write(b);
} catch (IOException e) {
// Exception handling
}
}
}
如果您能帮我解决这个问题,那就太好了。修改允许打开文件的最大数量是没有选择的,因为应用程序应该处理比其当前状态更多的数据。
更新
我更改了一些内容以减少内存使用,但在程序写入 5016 个文件后仍然出现相同的错误。我浏览了整个代码,但无法弄清楚任何事情。我可以想象异常被某种方式触发的唯一地方是在调用建立连接的 API 期间,但我在这里也没有看到任何错误。
protected static CoreEntity[] sendGET(CoreEntity[] resultList, String path) throws IOException, JSONException {
return handleResponse(resultList, getConnection(path, GET_REQUEST));
}
private static HttpURLConnection getConnection(String path, String requestMethod) throws IOException {
URL url = new URL(REQUEST_URL + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("accept", "application/json");
connection.setConnectTimeout(50000);
connection.setReadTimeout(50000);
connection.setRequestMethod(requestMethod);
initializeGSON();
return connection;
}
private static CoreEntity[] handleResponse(CoreEntity[] resultList, HttpURLConnection connection) throws IOException {
final int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) { // Success
try (InputStreamReader reader = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(reader)) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
reader.close();
in.close();
JSONArray jsonArray = getJSONAsArray(response.toString());
resultList = (CoreEntity[]) Array.newInstance(resultList.getClass().getComponentType(), jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
resultList[i] = (CoreEntity) GSON.fromJson(jsonArray.get(i).toString(), resultList.getClass().getComponentType());
} catch (IOException | JSONException e) { e.printStackTrace(); }
} else { // Error
System.out.println("Request failed with error code: " + status);
}
connection.disconnect();
return resultList;
}
解决方案
我正在将多个文件写入单个目录,其中文件的名称对应于目录中的文件数量。为了得到这个长度,我使用了Files.list(Paths.get(directory)).count()
. 显然,这会打开目录中导致上述异常的所有文件。我用它替换了它,new File(getRootDirectory() + directory + "/").list().length
现在一切都按预期工作。一个很大的帮助是苹果的活动监视器,我注意到打开的文件来自特定的方法。
尽管您无法直接帮助我,但感谢你们为我指明了正确的方向。
推荐阅读
- ssl - 一张图片的 Bigcommerce https 错误
- ios - iOS Vision API 重采样导致结果冲突,?
- java - WebView 加载页面时触发动作
- html - 如何调整图像大小,使它们与 CSS 完美匹配?
- c++ - Boost Hana:将 Hana 类型转换为 std::string 的
- amazon-web-services - 使用 AWS SageMaker create-training-job 命令:输入错误
- mongodb - mongoDB:删除字段以使其无效会更好吗?
- python - python随机二进制列表,均匀分布
- video - Flutter 支持 rstp/rtmp 视频播放器吗?
- google-apps-script - 谷歌脚本在标签中提取电子邮件的收件人