Java NIO逐行读文件并写文件
来源:互联网 发布:logo的设计软件 编辑:程序博客网 时间:2024/06/05 11:26
package com.sogou.study.nio.file;/** * Created by denglinjie on 2016/9/27. */import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class TestFileNio { public static void main(String args[]) throws Exception{ int bufSize = 100; File fin = new File("D:\\test\\file1.txt"); File fout = new File("D:\\test\\file2.txt"); FileChannel fcin = new RandomAccessFile(fin, "r").getChannel(); ByteBuffer rBuffer = ByteBuffer.allocate(bufSize); FileChannel fcout = new RandomAccessFile(fout, "rws").getChannel(); ByteBuffer wBuffer = ByteBuffer.allocateDirect(bufSize); readFileByLine(bufSize, fcin, rBuffer, fcout, wBuffer); System.out.print("OK!!!"); } public static void readFileByLine(int bufSize, FileChannel fcin, ByteBuffer rBuffer, FileChannel fcout, ByteBuffer wBuffer){ String enterStr = "\n"; try{ byte[] bs = new byte[bufSize]; StringBuffer strBuf = new StringBuffer(""); while(fcin.read(rBuffer) != -1){ int rSize = rBuffer.position(); rBuffer.rewind();<span style="white-space:pre"></span>//将position置为0,为读做准备 rBuffer.get(bs);<span style="white-space:pre"></span>//从上述position=0的位置开始读 rBuffer.clear(); String tempString = new String(bs, 0, rSize); int fromIndex = 0; int endIndex = 0; //查找换行符符号\n,如果找到了,则写文件,如果没有找到则继续读取 while((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1){ String line = tempString.substring(fromIndex, endIndex); line = strBuf.toString() + line; writeFileByLine(fcout, line); strBuf.delete(0, strBuf.length()); fromIndex = endIndex + 1; } if(rSize > tempString.length()){ strBuf.append(tempString.substring(fromIndex, tempString.length())); }else{ strBuf.append(tempString.substring(fromIndex, rSize)); } } } catch (IOException e) { e.printStackTrace(); } } public static void writeFileByLine(FileChannel fcout, String line){ try { fcout.write(ByteBuffer.wrap(line.getBytes()), fcout.size()); } catch (IOException e) { e.printStackTrace(); } }}
上述代码中所用到的ByteBuffer,关于它的介绍参考如下链接,用图解的方式解释的非常形象:
http://blog.csdn.net/baple/article/details/12749005
0 0
- Java NIO逐行读文件并写文件
- Java NIO 写文件
- java逐行读逐行写
- java逐行读逐行写
- Java NIO读,写,拷贝文件
- File IO(NIO.2):读、写并创建文件
- 在Java中如何逐行地写文件?
- 逐行读TXT文件
- 从txt里面读文件并逐行输出到控制台
- java逐行读取txt.文件
- 逐行读取文件内容(java)
- Java 逐行读写 TXT 文件
- Java逐行读写TXT文件
- java nio 常见的nio类, nio 写文件方法, nio 比io 的优势
- java从数据源读文件流并写文件
- Java NIO读/写入文件
- python读取大文件并逐行写入另外一个文件
- Java:对文件A.txt内部数据逐行排序,并写入B.txt
- 哈希
- Linux 查看文本命令(cat tac rev head tail)
- linux uniq命令(去除排序之后的重复)
- Action Bar
- QQ播放器 “复读”功能
- Java NIO逐行读文件并写文件
- linux dirname目录 basename文件 命令
- linux 非目录所有者 无权限访问
- JSP+Servlet+JavaBean实现用户登陆,用户退出
- linux awk 学习笔记一(print 、变量、数组)
- linux awk 学习笔记二(正则匹配、数学、逻辑匹配)
- linux awk 学习笔记三(结构化命令、函数)
- Swift 3.0 -字典
- windows设置代理上网