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

问题描述 投票:0回答:1

我的应用程序以某种方式抛出“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
        }
    }
}

如果你能帮助我解决这个问题,那就太好了。修改允许打开的最大文件数是没有选项的,因为应用程序应该处理比当前状态多得多的数据。

UPDATE

我改变了一些东西来减少内存的使用,但是在程序写入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;
}
java filenotfoundexception fileoutputstream
1个回答
0
投票

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

虽然你不能直接帮助我,但是谢谢你们指点我正确的方向。

© www.soinside.com 2019 - 2024. All rights reserved.