首页 > 解决方案 > 将变量从一种方法传递到另一种方法时不一致

问题描述

我有一个我无法解决的问题,而且我没有想到它可能会解决。

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

这些是我的课:

    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对象是一样的

标签: javainputstream

解决方案


当您将流传递到 时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

推荐阅读