【问题标题】:What's the difference between reading from a string and reading from an inputstream?从字符串读取和从输入流读取有什么区别?
【发布时间】:2018-03-21 14:13:22
【问题描述】:

在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

所以我想知道使用这两种方法有什么区别,每种方法有什么优缺点,因为第二种方法更容易和简单,还有其他更好的方法可以实现吗?

【问题讨论】:

    标签: java input stream inputstream


    【解决方案1】:

    直截了当,最佳

    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)。

    【讨论】:

    • 我明白了,所以如果我只阅读英文拉丁字符和数字,那么我使用最简单的形式没有问题,非常感谢
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-22
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2014-05-09
      相关资源
      最近更新 更多