1

我有一个代码,可以在其中读取网络驱动器上的图像。我阅读了数千张图片,但只是有时我偶尔会遇到以下异常。

java.io.IOException: An unexpected network error occurred
    at java.base/sun.nio.ch.FileDispatcherImpl.read0(Native Method)
    at java.base/sun.nio.ch.FileDispatcherImpl.read(FileDispatcherImpl.java:54)
    at java.base/sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:276)
    at java.base/sun.nio.ch.IOUtil.read(IOUtil.java:245)
    at java.base/sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:223)
    at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:65)
    at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:109)
    at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:103)
    at java.base/java.io.InputStream.read(InputStream.java:205)

下面是我得到它的代码

`

public static int getEPSSectionOffset(File file) throws Exception {
    int result = 0;
    try (InputStream inputStream =  
      Files.newInputStream(Paths.get(file.getAbsolutePath()),StandardOpenOption.READ);) {
      byte[] fourBytes = new byte[4];
      int totalBytesRead = inputStream.read(fourBytes);
      if (log.isDebugEnabled())
        log.debug("Total bytes read is " + totalBytesRead + " for file " + file.getPath());

      if (fourBytes[0] == (byte) 0xC5 && fourBytes[1] == (byte) 0xD0 && fourBytes[2] == (byte) 0xD3 
      && fourBytes[3] == (byte) 0xC6) {
        totalBytesRead = inputStream.read(fourBytes);
        if (log.isDebugEnabled())
          log.debug("Total bytes read is " + totalBytesRead + " for file " + file.getPath());

        result = makeInt(fourBytes);
      }
      return (result);
    } catch (Exception e) {
      log.error("Get EPS Section Offset - " + e.getMessage(), e);
    }
    return 0;
  }`

我在这一行得到了异常 - int totalBytesRead = inputStream.read(fourBytes);

4

1 回答 1

1

您可能对底层网络连接有疑问。这不是您可以解决的问题,网络总会出现间歇性问题。这意味着您将不得不忍受它,并减轻其影响。

也许是这样的:

public static int getEPSSectionOffsetWithRetry(File file) {
   int retryCount = 3;
   for(int i=0; i < retryCount i++) {
       try {
           int offset = getEPSSectionOffset()
           return offset;
       } catch (IOException ex) {
          //Maybe wait i little
       }
   }
   throw new IOException("Retry count exceeded");
}
于 2021-01-29T10:32:53.650 回答