将字符串传递给输入流
Passing string to input stream
有人写了一个 class 我想测试一下。它看起来像:
public class foo <E>{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
do_stuff(scan.nextInt());
}
}
我有另一个 class 试图测试上述函数的主要方法,如下所示:
public class Test{
public static void main(String[] args){
System.in.read("5".getBytes());
foo.<Integer>main(new String[]{});
}
}
基本上,我正在尝试使用测试 class 将输入馈送到流中,该流将很快被 foo 中的扫描器读取。我根本无法更改 foo,因为它是别人的代码。
为什么这不起作用?正确的做法是什么?
您的 System.in.read("5".getBytes())
所做的是将一个字节数组传递给 read
方法,该方法尝试用用户输入填充它。它完全忽略了您放入该字节数组的数据。
您必须调用 System.setIn()
来更改连接到 System.in
的流:
System.setIn(new ByteArrayInputStream("5".getBytes()));
foo.<Integer>main(new String[]{});
有人写了一个 class 我想测试一下。它看起来像:
public class foo <E>{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
do_stuff(scan.nextInt());
}
}
我有另一个 class 试图测试上述函数的主要方法,如下所示:
public class Test{
public static void main(String[] args){
System.in.read("5".getBytes());
foo.<Integer>main(new String[]{});
}
}
基本上,我正在尝试使用测试 class 将输入馈送到流中,该流将很快被 foo 中的扫描器读取。我根本无法更改 foo,因为它是别人的代码。
为什么这不起作用?正确的做法是什么?
您的 System.in.read("5".getBytes())
所做的是将一个字节数组传递给 read
方法,该方法尝试用用户输入填充它。它完全忽略了您放入该字节数组的数据。
您必须调用 System.setIn()
来更改连接到 System.in
的流:
System.setIn(new ByteArrayInputStream("5".getBytes()));
foo.<Integer>main(new String[]{});