Normally to read contents from a file present in your resources directory, we can do it by opening up an Input Stream.
this.getClass().getClassLoader().getResourceAsStream("yourJsonFile.json");
this works fairly well when calling it synchronously.
In case of handling this concurrently, it throws an I/O Exception with the below message.
Too many open files
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:91)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at java.nio.file.Files.newBufferedReader(Files.java:2784)
at java.nio.file.Files.lines(Files.java:3744)
at java.nio.file.Files.lines(Files.java:3785)
为了使内容更全面,假设我们正在使用InputStream读取文件,并在从文件中读取所有行后立即将其关闭。在这种情况下,读取文件时会打开一个I / O端口。但是,当并发调用发生时,它将尝试一次打开多个端口。 这不仅会阻碍程序的进度,而且会降低性能,因为I / O操作在时间消耗方面要高一些。
为了解决这种情况,我们可以通过将IO流封装到兼容的Data Structure中来对其进行缓存,因此HashMap可能是理想的选择。有一个可以返回HashMap的方法。现在,每当我们需要读取文件时,我们所需要做的就是调用此方法,以使您的文件内容随时可用。
这是当前正在处理此方案的方法之一。
还有其他更有效的方法吗?