JAVA NIO 读写文件

来源:互联网 发布:js json遍历 编辑:程序博客网 时间:2024/05/22 15:44
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);}}}}}


原创粉丝点击