我有一个我无法解决的问题,但我没想到它可以解决。
我有一个类,我从主要方法向其传递 InputStream,问题是当使用 AWS 的 IOUtils.toString 类或 commons-io 的 IOUtils 将 InputString 转换为 String 时,它们返回 空字符串 不管问题是什么,因为在主类中,它工作正常并返回它应该的字符串,但是当我在另一个类中使用它时(没有做任何事情),它返回空字符串给我。
这些是我的类(class):
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对象是一样的
最佳答案
你不能的原因是你只能从流中读取一次。
为了能够读取两次,必须调用reset()
方法让它回到开头。阅读完毕调用reset()
即可再次阅读!
某些来源不支持重置它,因此您实际上必须重新创建流。要检查源是否支持它,请使用流的 markSupported()
方法!
关于java - 将变量从一种方法传递到另一种方法时不一致的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51616272/