在String中将String byte []转换为Raw byte []

时间:2012-11-04 08:59:39

标签: java string bytearray

如果我有byte []以这种格式保存字符串:

abcd 546546545 dfdsfdsfd 5415645

我知道这些数字是整数类型。使用byte[]方法获取原始String.split()的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

这个答案是基于以下假设(没有明确保证你发布的内容):

  • 您目前正在直接从文件中读取字节
  • 该文件存储在VM的默认编码
  • 您想忽略非十进制数字的所有内容
  • 您想要生成byte[],其中每个字节包含与文件中找到的小数位对应的数值

根据这些假设,我会解决这个问题如下:

public byte[] getDigitValues(String file) throws IOException {
    FileReader rdr = new FileReader(file);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        rdr = new BufferedReader(rdr);
        for (char c = rdr.read(); c != -1; c = rdr.read()) {
            if (c >= '0' && c <= '9') {
                bos.write(c - '0');
            }
        }
    } finally {
        if (rdr != null) {
            try { rdr.close(); }
            catch (IOException e) {
                throw new IOException("Could not close file", e);
            }
        }
    }
    return bos.toByteArray();
}

在Java 7中,我使用try-with-resources statement

public byte[] getDigitValues(String file) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (Reader rdr = new BufferedReader(new FileReader(file))) {
        for (. . .
    }
    return bos.toByteArray();
}
相关问题