读取S3文件时"java.net.SocketException:Socket已关闭"

Fgb*_*nch 6 java file-io amazon-s3

我正在尝试从S3读取csv文本文件,然后将其每个行发送到分布式队列以进行处理.

当试图读取它时,我得到"java.net.SocketException:Socket is closed"正在读取的文件的不同点的异常(在不同的执行中).这是代码:

      AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(MyClass.class.getResourceAsStream("myCredentials.properties")));

        String bucketName = "myBucket";
        String key = "myFile";  

        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));

        InputStream in = object.getObjectContent();

        BufferedReader readerS3 = new BufferedReader(new InputStreamReader(in, Charset.forName(fileInfo.getEncoding())));

        try {
            String line = null;
            while ((line = readerS3.readLine()) != null) {
                // Sending the line to a distributed queue
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
Run Code Online (Sandbox Code Playgroud)

有关如何解决这个问题的任何想法?

更新:

从我第二次运行该方法时发生此异常,如果我停止整个程序并再次运行它,那么我第一次运行该方法就可以了.

yeg*_*256 6

正如在评论中质疑"JSN"建议,问题是,你需要配置AmazonS3ClientConfiguration:

ClientConfiguration config = new ClientConfiguration();
config.setSocketTimeout(0);
AmazonS3 s3 = new AmazonS3Client(/* credentials */, config);
Run Code Online (Sandbox Code Playgroud)


Mar*_*arc 1

也许你应该在你的finally而不是'in'中关闭readerS3。即关闭最外面的对象,这可以关闭它所包裹的子对象。

如果您先关闭“in”,则 InputStreamReader 和 BufferedReader 仍处于打开状态,并且如果它们尝试对它们包装的对象执行任何操作,则它们已经被关闭。