从一种方法传递给另一种方法时变量不一致

时间:2018-07-31 14:51:22

标签: java inputstream

我有一个我无法解决的问题,而且我认为这不可能。

我有一个要从主方法传递InputStream的类,问题是当使用AWS的IOUtils.toString类或commons-io的IOUtils将InputString转换为String时,它们返回 一个空字符串 不管是什么问题,由于在主类中可以正常工作并返回应有的String,但是当我在其他类中使用它(未做任何事情)时,它将空字符串返回给我。

这些是我的课程:

    public class Main {

    public static void main(String [] args) throws IOException {

        InputStream inputStream = new ByteArrayInputStream("{\"name\":\"Camilo\",\"functionName\":\"hello\"}".getBytes());
        OutputStream outputStream = new ByteArrayOutputStream();

        LambdaExecutor lambdaExecutor = new LambdaExecutor();


        String test = IOUtils.toString(inputStream); //this test variable have "{\"name\":\"Camilo\",\"functionName\":\"hello\"}"
        lambdaExecutor.handleRequest(inputStream,outputStream);
    }
}

还有:

    public class LambdaExecutor{

    private FrontController frontController;
    public LambdaExecutor(){
        this.frontController = new FrontController();
    }

    public void handleRequest(InputStream inputStream, OutputStream outputStream) throws IOException {
        //Service service = frontController.findService(inputStream);

        String test = IOUtils.toString(inputStream); //this test variable have "" <-empty String

        System.exit(0);
        //service.execute(inputStream, outputStream, context);
    }
}

我使用了调试工具,并且两个类中的InputStream对象都是相同的

2 个答案:

答案 0 :(得分:2)

之所以不能,是因为您只能从流中读取一次。

要能够阅读两次,必须调用reset()方法以使其返回开头。阅读后,致电reset(),您可以再次阅读!

某些来源不支持重置它,因此您实际上必须再次创建流。要检查源是否支持它,请使用流的markSupported()方法!

答案 1 :(得分:2)

当您将流传递到handleRequest()时,您已经消耗了流:

public static void main(String [] args) throws IOException {

    InputStream inputStream = new ByteArrayInputStream("{\"name\":\"Camilo\",\"functionName\":\"hello\"}".getBytes());
    OutputStream outputStream = new ByteArrayOutputStream();

    LambdaExecutor lambdaExecutor = new LambdaExecutor();


    String test = IOUtils.toString(inputStream); //this consumes the stream, and nothing more can be read from it
    lambdaExecutor.handleRequest(inputStream,outputStream);
}

取出后,该方法按您在评论中所说的那样工作。

如果您希望数据可重复使用,则如果您再次想要相同的数据,则必须使用reset()方法,或者关闭并重新打开流以使用以下对象来重新使用该对象不同的数据。

// have your data 
byte[] data = "{\"name\":\"Camilo\",\"functionName\":\"hello\"}".getBytes();
// open the stream
InputStream inputStream = new ByteArrayInputStream(data);
...
// do something with the inputStream, and reset if you need the same data again
if(inputStream.markSupported()) {
    inputStream.reset();
} else {
    inputStream.close();
    inputStream = new ByteArrayInputStream(data);
}
...
// close the stream after use
inputStream.close();

使用完流后始终关闭流,或使用try块来利用AutoCloseable;您可以对输出流执行相同的操作:

try (InputStream inputStream = new ByteArrayInputStream(data);
    OutputStream outputStream = new ByteArrayOutputStream()) {
    lambdaExecutor.handleRequest(inputStream, outputStream);
} // auto-closed the streams
相关问题