java - 将变量从一种方法传递到另一种方法时不一致
问题描述
我有一个我无法解决的问题,而且我没有想到它可能会解决。
我有一个从主方法传递 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对象是一样的
解决方案
当您将流传递到 时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
推荐阅读
- html - 定义尺寸
- liquibase - Liquibase - 生成更改日志
- c - Scanf while 循环影响循环外的下一个 scanf
- arduino - 如何使用 AsyncWebServer 下载 SPIFFS 文件?
- python - 以编程方式将许多参数及其名称作为键添加到 dict 的最快方法
- mongodb - 从 MongoDB 导出所有电子邮件地址
- ios - 一些应用程序发出的警报超过 64(本地通知),有什么方法可以管理这个吗?
- javascript - 在幕后,回调是如何在 Javascript 中编码的?
- c++ - 如何以对数时间访问 c++ std::set 中的第 k 个元素?
- php - PayPal IPN 沙盒 - 更改通知 URL 不会更新