今天老同学发给我一个NIO读取读片的类,看看是什么问题,主要源代码如下
public static byte[] readNIO(String imageUrl) throws IOException {
byte[] result = new byte[1024000];
URL url = new URL(imageUrl);
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
ByteBuffer buffer = ByteBuffer.allocate(1024000);
readableByteChannel.read(buffer);
result = buffer.array();
return result;
}
public static void main(String[] args) {
try {
getFile(readNIO("https://csdnimg.cn/release/edu/resource/images/special/block_chain/block1title.png"),"D:\\","a11.png");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据byte数组,生成文件
*/
public static void getFile(byte[] bfile, String filePath,String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath+"\\"+fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
首先看到的问题是创建目录的地方,做了修改,如下
File dir = new File(filePath);
if (!dir.exists()) {//如果不存在
dir.mkdirs();
}
if (!dir.isDirectory()) {//如果不是目录
dir.delete();
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
然后跑一边代码,发现图片只保存了一半,应该是没有读取完全,所以问题应该是在读取的地方,然后把读取的大部分代码稍微修改下,打印下看看
可以看到循环读取了两次,所以基本上是没有读取完的情况,所以作如下修改,循环读取并写入ByteArrayOutputStream里面,然后清空缓存,在继续读取,最后再从这里面返回字节数据,这样就不会造成读取不完整的问题了。
public static byte[] readNIO(String imageUrl) throws IOException {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
URL url = new URL(imageUrl);
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
ByteBuffer buffer = ByteBuffer.allocate(1024000);
int len = 0;
while ((len = readableByteChannel.read(buffer)) > 0) {
System.out.println(len);
byteArray.write(buffer.array(), 0, len);
buffer.clear();
}
return byteArray.toByteArray();
}