Java NIO逐行读文件并写文件


/**
 * Created by scott on 2019/7/19.
 */
public class test {
    public static void main(String args[]) throws Exception {
        int bufSize = 100;
        File fin = new File("C:\\Users\\User\\Desktop\\localhost_access_log.2019-07-16.txt");
        File fout = new File("C:\\Users\\User\\Desktop\\localhost_access_log.2019-07-16_AAAA.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();
                rBuffer.get(bs);
                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;
                    System.out.println(line);
                    ;

                    if (line.contains("1111111111111111")) {
                        writeFileByLine(fcout, line + "\n");
                    }

                    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();
        }
    }
}