【发布时间】:2019-09-17 21:20:54
【问题描述】:
我的应用程序以某种方式抛出“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;
}
【问题讨论】:
-
在 * writeToFile* 方法中使用 synchronized(this) { ... }
-
dao.getAll()是否有可能返回并行流? -
这是一个简单的API调用,没有并行流。
-
您的代码中缺少某些内容。您正在流式传输
Double[][],它将为您提供Double[]的流,但DataFileWriter.writeToFile()只需要Double。是否发生了一些您错过在这里复制的转换,或者是一些writeToFile(String filename, Double[] data)被调用了? -
此外,为每个
Double值打开(重新)文件然后再次关闭它可能会非常慢。
标签: java filenotfoundexception fileoutputstream