0

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

abcd 546546545 dfdsfdsfd 5415645

我知道这些数字是整数类型。byte[]在不使用方法的情况下,最好的方法是String.split()什么?

4

1 回答 1

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 语句

public byte[] getDigitValues(String file) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try (Reader rdr = new BufferedReader(new FileReader(file))) {
        for (. . .
    }
    return bos.toByteArray();
}
于 2012-11-04T15:27:49.157 回答