java将文件读取为byte[]数组 ByteArrayOutputStreamreadFile
程序员文章站
2024-02-24 20:33:16
...
public byte[] readFile(String pathStr){
InputStream is = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
try {
is = new FileInputStream(pathStr);// pathStr 文件路径
while ((n = is.read(b)) != -1) {
out.write(b, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return out.toByteArray();
}
InputStream is = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
try {
is = new FileInputStream(pathStr);// pathStr 文件路径
while ((n = is.read(b)) != -1) {
out.write(b, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return out.toByteArray();
}