public byte[] getBytes(String filePath) {
try {
InputStream in = null;
DataInputStream dis = null;
HttpURLConnection connection = null;
URL server = new URL(filePath);
connection = (HttpURLConnection) server.openConnection();
connection.connect();
in = connection.getInputStream();
dis = new DataInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = 0;
while ((ch = dis.read()) != -1) {
baos.write(ch);
}
byte[] imageData = baos.toByteArray();
if (baos != null) {
baos.close();
baos = null;
}
if (dis != null) {
dis.close();
dis = null;
}
if (in != null) {
in.close();
in = null;
}
if (connection != null) {
connection.disconnect();
connection = null;
}
return imageData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
try {
InputStream in = null;
DataInputStream dis = null;
HttpURLConnection connection = null;
URL server = new URL(filePath);
connection = (HttpURLConnection) server.openConnection();
connection.connect();
in = connection.getInputStream();
dis = new DataInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = 0;
while ((ch = dis.read()) != -1) {
baos.write(ch);
}
byte[] imageData = baos.toByteArray();
if (baos != null) {
baos.close();
baos = null;
}
if (dis != null) {
dis.close();
dis = null;
}
if (in != null) {
in.close();
in = null;
}
if (connection != null) {
connection.disconnect();
connection = null;
}
return imageData;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
从URL读取字节流
本文介绍了一种通过URL获取文件并将其转换为字节数组的方法。使用了Java的HttpURLConnection类来建立连接,并通过DataInputStream读取数据到ByteArrayOutputStream中,最终转化为byte[]形式。
1813

被折叠的 条评论
为什么被折叠?



