您的位置:首页 > 编程语言 > Java开发

JAVA NIO 读写文件

2017-12-07 13:43 375 查看
private static boolean write(byte[] data, String diskSrcPath, String fileName, String format) {
File f = new File(diskSrcPath);
if (!f.exists()) {
f.mkdirs();
}
f = new File(diskSrcPath + "/" + fileName + "." + format);
FileOutputStream fos = null;
FileChannel fc = null;
try {
if (!f.exists()) {
fos = new FileOutputStream(f);
fc = fos.getChannel();
ByteBuffer bb = ByteBuffer.allocate(data.length);
bb.put(data);
bb.flip();
fc.write(bb);
bb.clear();
fc.close();
fos.close();
fc = null;
fos = null;
bb = null;
}
} catch (Exception e2) {
log.error(e2);
} finally {
if (fc != null) {
try {
fc.close();
} catch (IOException e) {
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
return true;
}
// 这个是直接通过response流输出
private static void reader(HttpServletResponse response, String type, String path, String fileName) {
File f = new File(type + path);
if (!f.exists()) {
RequestUtils.responseJSON(response, new Result(ResultCode.M404));
} else {
FileInputStream file = null;
FileChannel fc = null;
try {
if (StringUtils.isNotBlank(fileName)) {
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
}
file = new FileInputStream(f);
fc = file.getChannel();
ByteBuffer b = ByteBuffer.allocate(2048);
b.clear();
while (fc.read(b) > 0) {
response.getOutputStream().write(b.array());
b.clear();
}
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception e) {
log.error("输出文件异常", e);
RequestUtils.responseJSON(response, new Result(ResultCode.M500).formatMsg(e.getMessage()));
} finally {
if (fc != null) {
try {
fc.close();
} catch (IOException e) {
log.error("输出文件异常", e);
}
}
if (file != null) {
try {
file.close();
} catch (IOException e) {
log.error("输出文件异常", e);
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: