FileOutputStream抛出FileNotFoundException(打开的文件太多)

时间:2019-04-29 09:10:38

标签: java filenotfoundexception fileoutputstream

我的应用程序以某种方式引发了“ java.io.FileNotFoundException:/ file / path(打开的文件过多)”,我不知道是哪个部分导致了此异常,因为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;
}

1 个答案:

答案 0 :(得分:0)

我正在将多个文件写入一个目录,其中文件名与目录中的文件数量相对应。为了获得此长度,我使用了Files.list(Paths.get(directory)).count()。显然,这会打开目录中导致上述异常的所有文件。我将其替换为new File(getRootDirectory() + directory + "/").list().length,现在一切正常。苹果的活动监视器非常有帮助,我注意到打开的文件来自特定的方法。

尽管您无法直接帮助我,但谢谢你们为我指明了正确的方向。