[英]Converting String byte [] into Raw byte[] in java
如果我有一個byte []
以這種格式保存字符串:
abcd 546546545 dfdsfdsfd 5415645
而且我知道數字是整數類型。 使用String.split()
方法從中獲取原始byte[]
的最佳方法是什么?
該答案基於以下假設(您發布的內容顯然不保證其中的任何一項):
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.