Ad

Stream Closed Error When Getting Charset

I'm having issues with the following code:

try (
      InputStream is = new FileInputStream(file);
      BufferedReader br = new BufferedReader(
                   new InputStreamReader(is,
                     Charset.forName(SidFileUtils.charsetDetection(is))
                   )
                 );
    ) {

        br.readLine();
        br.readLine();

        for (String line = br.readLine() ; line != null ; line = br.readLine()) {
            lines.add(line);
        }
    } catch (ExceptionTechnique | IOException e) {
        LOG.error("Erreur lors de la lecture du fichier " + file.getName(), e);
    }

This part of the code: Chasrset.forName(...) is giving me a Stream Closed error. I think it's because I'm using the InputStream item twice and it has already been consumed but I'm not sure.

Can you help me understand what is wrong with this code please ?

Thanks a lot in advance !

Ad

Answer

Yes, the charsetDetection has no other option to read the stream further. Some streams can mark and reset the read position when the specific InputStream supports it.

if (in.markSupported()) {
    final int maxBytesNeededForDetection = 8192;
    in.mark(maxBytesNeededForDetection);
    ... do the detection
    in.reset();
} else {
    throw IllegalState();
}

BufferedInputStream indeed supports it, but only upto the buffer size; otherwise an IOException("Resetting to invalid mark"); is raised.

One then should specify the buffer size in the constructor.

In this case it seems no mark/reset is used by the detection. Quite logical because of the partial coverage of such a technique.

Charset charset = null;
try (InputStream is = new FileInputStream(file)) {
    Charset charset = Charset.forName(SidFileUtils.charsetDetection(is));
}
if (charset != null) {
    ...
}
Ad
source: stackoverflow.com
Ad