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); } } } } }
相关文章推荐
- JAVA之NIO按行读写大文件,完美解决中文乱码问题
- 【JavaNIO的深入研究4】内存映射文件I/O,大文件读写操作,Java nio之MappedByteBuffer,高效文件/内存映射
- Java文件读写IO/NIO及性能比较总结
- java对比IO和NIO的文件读写性能测试
- 【JavaNIO的深入研究4】内存映射文件I/O,大文件读写操作,Java nio之MappedByteBuffer,高效文件/内存映射
- Java文件读写IO/NIO及性能比较总结
- JAVA I/O 、NIO 文件读写性能对比
- java:NIO读写文件的示例
- Java文件读写IO/NIO及性能比较总结
- Java文件读写IO/NIO及性能比较总结
- Java nio(文件读写 实例解析)
- Java文件读写IO/NIO及性能比较详细代码及总结
- Java NIO 读写文件
- java对比IO和NIO的文件读写性能测试
- 2015我想和Java聊聊之NIO读写文件
- 使用java的java.nio.channels.FileLock,实现程序对文件的独占读写.
- 大数据量的文件读写 java nio的完全发挥
- java nio 超大文件的读写
- JAVA之NIO按行读写大文件,完美解决中文乱码问题
- java中对图象文件的处理(读写以及转换)