Java文本文件切割

之前了解过用Java切割文件,采用的是字节流的方式读取文件,然后发现存在一个问题,就是前面的文件是正常编码的,后面的文件会乱码。于是针对个人需求(2.3G的文本文件无法打开),采用按行读取,即一行一行读取文件然后再存入到新的文本中。
具体代码如下:

    /**
     * 
     * @Description 文件分割
     * @param src 分割文件路径
     * @param maxline 最大行数(即每个文件中存储的行数)
     * @throws IOException
     */
    public static void splitFileDemo(String path,int maxline) throws IOException {
        FileInputStream fis = new FileInputStream(path);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        // 获取文件名
        String fileName = path.substring(0, path.indexOf("."));
        // 获取文件后缀
        String endName = path.substring(path.lastIndexOf("."));
        try {
            int i = 0;
            boolean end = false;//判断文件是否读取完毕
            while (true) {
                if (end)
                    break;
                StringBuffer sb = new StringBuffer();
                sb.append(fileName);
                sb.append("_data");
                sb.append(i);
                sb.append(endName);
                System.out.println(sb.toString());// 新生成的文件名
                // 写入文件
                FileOutputStream fos = new FileOutputStream(new File(
                        sb.toString()));
                OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                BufferedWriter bw = new BufferedWriter(osw);
                String line = "";// 一行行读取文件
                int m = 1;
                while((line = br.readLine())!=null ){
                    bw.write(line+"\t\n");
                    if(m>=maxline){
                        break;
                    }                       
                    m++;
                }
                if(m<maxline)
                    end = true;
                i++;
                //关闭写入流
                bw.close();
                osw.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭输入流
            br.close();
            isr.close();
            fis.close();
        }
        System.out.println("--- 文件分割完成 ---");

    }

测试代码:

import java.io.IOException;

public class TestSplitByLine {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        CopyOfsplitFile_MergeFileByLine.splitFileDemo(
                "E:\\TestData\\splitTest\\hello.txt", 
                4);
    }

}

测试结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u012485480/article/details/80524976