File操作-使用NIO进行文件的读写与复制
来源:互联网 发布:我的世界1.7.10java 编辑:程序博客网 时间:2024/05/22 13:03
Tips-1:并不是所有的IO流类都支持NIO操作的,支持的类有FileInputStream、FileOutputStream和RandomAccessFile.
/*文件读取,返回读取内容*/ public static String fileReader(File fileName){ String fileContent = null; FileInputStream fis = null; FileChannel fc = null; ByteBuffer bb ; try { fis = new FileInputStream(fileName); fc = fis.getChannel(); bb = ByteBuffer.allocate(10000); /*读入到bb里面*/ fc.read(bb); /*这里一定不要省略*/ bb.flip(); fileContent = new String(bb.array()); } catch (Exception e) { e.printStackTrace(); }finally{ try { fc.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return fileContent; } /* fileName:要写入的目标文件; s:要写入的信息; */ public static void fileWriter(File fileName,String s){ String fileContent = null; FileOutputStream fos = null; FileChannel fc = null; byte[] bts = s.getBytes(); try { fc = new FileOutputStream(fileName).getChannel(); ByteBuffer bb = ByteBuffer.allocate(bts.length); /*将bts放入bb里面*/ bb.put(bts); bb.flip(); /*从缓冲区块读出*/ fc.write(bb); } catch (Exception e) { e.printStackTrace(); }finally{ try { fc.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /*进行文件复制*/ public static void copy(String srcFile,String destFile){ long begin = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel in = null; FileChannel out =null; ByteBuffer bb = null; try { /* get NIO read channel */ fis = new FileInputStream(srcFile); in = fis.getChannel(); /* get NIO write channel*/ fos = new FileOutputStream(destFile); out = fos.getChannel(); bb = ByteBuffer.allocate(100000); int len = 0; while((len = in.read(bb)) != -1){ /*在write前,set the limit and position*/ bb.flip(); /*write form position to limit */ out.write(bb); /*init positon/limit/capcity,prepare to the next loop*/ bb.clear(); } long end = System.currentTimeMillis(); System.out.println("use time :"+(end-begin)); out.close(); in.close(); fos.close(); fis.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
0 0
- File操作-使用NIO进行文件的读写与复制
- 使用NIO进行文件操作
- 使用IO进行文件的复制操作
- NIO文件读写操作
- 使用NIO读写文件
- 使用NIO复制文件
- 【Java】File类文件管理及IO读写、复制操作
- 使用FILE文件指针进行文件的操作相关函数
- C#使用DOM进行XML文件的读写操作介绍
- NIO中的File文件操作
- android File文件的读写操作
- 使用NIO进行快速的文件拷贝
- 使用NIO进行快速的文件拷贝
- 使用NIO进行快速的文件拷贝
- 用Qt进行文件的读写操作
- C#进行INI文件的读写操作
- 使用NIO与BIO复制文件性能对比
- 通过缓冲区进行文件复制的操作
- Android运行在主线程和子线程浅释
- JS Function.caller 和 arguments.callee学习
- 【Android H5移动开发】MUI框架的试用
- 二维数组搜索
- JS回调函数的理解
- File操作-使用NIO进行文件的读写与复制
- 移动网页 viewport(视口) 像素密度
- 扩展javascript内置对象
- 剑指offer--面试题35:第一个只出现一次的字符位置
- poj3393Lucky and Good Months by Gregorian Calendar
- Ubuntu找不到libSDL-1.2.so.0
- JNI开发之打包输出so库
- Rational Rose与UML教程
- 数据摘要算法的测试效率(SHA、MD5和CRC32)