if I have a byte []
which holds string in this format:
abcd 546546545 dfdsfdsfd 5415645
and I know the numbers are of type integer. What is the best way to get a raw byte[]
out of it, wihtout using String.split()
method?
This answer is based on the following assumptions (none of which are clearly warranted from what you have posted):
byte[]
where each byte contains the numeric value corresponding to the decimal digits found in the file With these assumptions, I would solve this problem as follows:
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();
}
In Java 7, I'd use the 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.