2017-10-10 78 views
0

在java中我可以做到这一点从字符串读取和从输入流读取之间有什么区别?

String sstream1 = 
     "as aasds 2 33\n" + 
     "this\n" + 
     "2.23\n"; 
InputStream stream = new ByteArrayInputStream(sstream1.getBytes()); 
Scanner cin = new Scanner(stream); 
Scanner cin2 = new Scanner(sstream1); 
String x1 = cin.next(); 
String x2 = cin.next(); 
int x3 = cin.nextInt(); 
int x4 = cin.nextInt(); 
String x5 = cin.next(); 
double x6 = cin.nextDouble(); 
Stream.of(x1, x2, x3, x4, x5, x6).forEach(o -> System.out.println(o)); 
x1 = cin2.next(); 
x2 = cin2.next(); 
x3 = cin2.nextInt(); 
x4 = cin2.nextInt(); 
x5 = cin2.next(); 
x6 = cin2.nextDouble(); 
Stream.of(x1, x2, x3, x4, x5, x6).forEach(o -> System.out.println(o)); 

我仍然得到同样的结果

as 
aasds 
2 
33 
this 
2.23 
as 
aasds 
2 
33 
this 
2.23 

,所以我想知道什么是使用这两种方法之间的区别,有什么优点和缺点对于每一个,因为第二个更容易和更简单,是否还有其他更好的方法来实现这一目标?

回答

0

向前伸直,最好

String sstream1 = ... // May contain Greek, Chinese, emoji, math symbols 
Scanner cin2 = new Scanner(sstream1); 

默认平台编码,来回转换为Unicode字符串。 特殊字符可能会出错。不是跨平台的。

InputStream stream = new ByteArrayInputStream(sstream1.getBytes()); 
Scanner cin = new Scanner(stream); 

明确的,跨平台的,但两次转换。

InputStream stream = new ByteArrayInputStream(sstream1.getBytes(StandardCharsets.UTF_8)); 
Scanner cin = new Scanner(stream, "UTF-8"); 

请注意,System.out也使用默认的平台字符集,这使测试代码无法使用。但扫描仅适用于所有Unicode的第一个或最后一个代码(使用Unicode的UTF-8)。

+0

我明白了,所以如果我只读英文拉丁字符和数字,那么我使用最简单的形式没有问题,非常感谢 –

0

InputStream是从资源获取信息的原始方法。它在不执行任何翻译的情况下逐字节地抓取数据。如果您正在读取图像数据或任何二进制文件,则这是要使用的流。

另一方面,当您使用String时,它是用于字符序列。您可以使用不同的字符编码样式并使用字符序列进行解码。因此,如果您只读取文本数据或字符,则可以使用String,但如果您使用的是图像或任何二进制文件,则必须处理进一步的处理和编码。