Java NIO(new/inputstream outputstream)使用通道、缓冲来操作流,所以要深刻理解这些概念,尤其是,缓冲中的数据结构(当前位置(position)、限制(limit)、容量(capacity))。
Channel(通道)、Buffer(缓冲区)、Selector(选择器)
/**
* @author sy
* @date 2020/2/13 19:31
*/
public class FileUtil implements Serializable {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
* 通过NIO获取byte[]
* @param filename
* @description 一般作用于从本地读取文件,通过httpServletResponse返回页面。
* @return
*/
public static byte[] toByteArray(String filename) {
File f = new File(filename);
if (!f.exists()) {
log.error("文件未找到!" + filename);
throw new RuntimeException("文件未找到");
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// 读取中....
}
return byteBuffer.array();
} catch (IOException e) {
//实际上应该自定义异常,统一异常处理
throw new RuntimeException("文件發生錯誤");
} finally {
try {
channel.close();
} catch (IOException e) {
throw new RuntimeException("文件發生錯誤");
}
try {
fs.close();
} catch (IOException e) {
throw new RuntimeException("文件發生錯誤");
}
}
}
/**
* copy文件
* @param src
* @param dst
* @description 一般作用于拷贝文件
* @throws IOException
*/
public static void copyFileUseNIO(String src,String dst) throws IOException{
//声明源文件和目标文件
FileInputStream fi = null;
FileOutputStream fo = null;
//获得传输通道channel
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//声明源文件和目标文件
fi = new FileInputStream(new File(src));
fo = new FileOutputStream(new File(dst));
//获得传输通道channel
inChannel = fi.getChannel();
outChannel = fo.getChannel();
//获得容器buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
//判断是否读完文件
int eof = inChannel.read(buffer);
if (eof == -1) {
break;
}
//重设一下buffer的position=0,limit=position
buffer.flip();
//开始写
outChannel.write(buffer);
//写完要重置buffer,重设position=0,limit=capacity
buffer.clear();
}
}catch (Exception e){
throw new RuntimeException("文件發生錯誤");
}finally {
try {
inChannel.close();
fi.close();
} catch (IOException e) {
throw new RuntimeException("文件發生錯誤");
}
try {
outChannel.close();
fo.close();
} catch (IOException e) {
throw new RuntimeException("文件發生錯誤");
}
}
}
}
注:资料有从各大网站参考,如有雷同,纯属意外。