Java-随机范围内分割大文件

需求

有一份文件,不大,通常电脑可以一次性读取。文件格式为若干行手机号码。将这个文件以随机范围[37~40]进行分割,也就是说当读取的行数满足随机范围的,则分割生成一个包含该行数小文件,剩余不足37行的,独自生成一个文件。
文件每行的内容,由原来”手机号”,更改为”手机号,text”格式。

语言

Java

实现

思路

生成[37~40]的随机数
通过commons.io进行读取原文件
通过StringBuilder进行格式更改,结合字符缓冲进行批量写入操作(写完注意清空
当满足随机范围,并且未到文件末行时,生成随机数行数的文件,到达文件末行时,无论是否满足随机范围,直接写入一个文件。

代码

public class SplitMobileFile {
  //写文件操作
    public void  writeFile(String writeDirectoryPath,String fileName,String sb){
        File file = new File(writeDirectoryPath+fileName);
        OutputStreamWriter writer = null;
        BufferedWriter bw = null;

        try {
            OutputStream os = new FileOutputStream(file);
            writer = new OutputStreamWriter(os);
            bw = new BufferedWriter(writer);
            FileUtils.writeStringToFile(file,sb ,true);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
             try {
                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    //读取文件操作
    public void readFile(String readFilePath,String writeDirectoryPath,String fileName){
        int count = 0;
        int flag = 0;
        Random rand = new Random();
        int randNum = rand.nextInt(3)+37;
        StringBuilder sb = new StringBuilder();
        LineIterator it = null;
        try {
            BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(readFilePath)));
            it= new LineIterator(reader);
            while (it.hasNext()) {
                String oneLine = it.nextLine()+",text";
                sb.append(oneLine+"\r\n");//windows下换行符需注意一下
                if(count<randNum&&it.hasNext()){
                    count+=1;
                }else{
                    flag+=1;
                    writeFile(writeDirectoryPath,fileName+"-"+String.valueOf(flag)+".txt",sb.toString());//将读取到的37~40行的文件内容一次性写入文件
                    count = 0;
                    sb = new StringBuilder();
                }    
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            it.close();
        }

    }

  //构造函数
    public SplitMobileFile(String readFilePath,String writeDirectoryPath,String fileName){
/*
 * readFilePath:读取文件的路径
 * writeDirctory:文件写入的目录路径
 * fileName,去掉后缀,比如想要生成hello-1.txt,只要输入hello即可
 */
        readFile(readFilePath,writeDirectoryPath,fileName);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

司小幽

真诚赞赏,手留余香。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值