简体   繁体   English

确定java中InputStream中下一次读取的类型

[英]determine type of next read in InputStream in java

Assuming that there is a file with a set of primitives written in it, however I do not know the type of primitives. 假设有一个文件中写有一组原语,但是我不知道原语的类型。

How can I read the data into the appropriate data type from my code? 如何从代码中将数据读入适当的数据类型? (that is read int into int, byte into byte etc) (即从int读取为int,将字节读取为byte等)

Or is this impossible? 还是这不可能?

You can try to convert it to a desired type ... if the conversion fails you try the next type and so on. 您可以尝试将其转换为所需的类型...如果转换失败,请尝试下一个类型,依此类推。 The final type being a String. 最终类型是字符串。

For example if the file would hold those lines: 例如,如果文件包含以下行:

1
1.3
12345324223423
test
true
false

You can test each value if it can be converted: 您可以测试每个值是否可以转换:

try {
    int value = Integer.parseInt(test);
}
catch (NumberFormatException e) {

    try {

        double value2 = Double.parseDouble(test);
    }
    catch (NumberFormatException ex) {

            ... and so on ... 
    }
}

I would start with the smallest and go to bigger, for instance: 例如,我将从最小的开始,然后扩大到更大:

  • Byte 字节
  • Integer 整数
  • Long
  • BigDecimal BigDecimal的
  • Boolean 布尔
  • Char 烧焦
  • and last String 最后一个字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM