java读取写入txt

public static void main(String[] args){
        readTxt("e:\\111.txt",35);
    }

    /**
     *
     * @param filePath  文件路径
     * @param num     生成文件总数(每一万生成一个txt)
     */
    public static  void readTxt(String filePath,int num){
        File file = new File(filePath);
        BufferedReader reader = null;
        try {
            //判断文件是否存在
            if (file.isFile() && file.exists()){
                ArrayList<String> AList = new ArrayList<String>();
                reader = new BufferedReader(new FileReader(file));
                String tempString = null;
                int line = 1;
                // 一次读入一行,直到读入null为文件结束
                while ((tempString = reader.readLine()) != null) {
                    // 显示行号
                    System.out.println("line " + line + ": " + tempString);
                    AList.add(tempString);
                    line++;
                }
                reader.close();
                //写入txt
                for (int i = 1; i <= num; i++) {
                    FileOutputStream fs = new FileOutputStream(new File(String.valueOf(i) + ".txt"));
                    PrintStream p = new PrintStream(fs);
                    if (i == 1) {
                        for (int j = 1; j <= 10000; j++) {
                            p.println(AList.get(j - 1));
                        }
                    } else if (i == 2) {
                        for (int j = 10001; j <= 20000; j++) {
                            p.println(AList.get(j - 1));
                        }
                    } else {
                        for (int j = ((i - 1) * 10000 + 1); j <= line - 1; j++) {
                            p.print(AList.get(j-1));
                            p.print("\r\n");
                        }
                    }
                    p.close();
                }
            }else{
                System.out.println("找不到指定的文件");
            }
        }catch (Exception e){
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

转载于:https://my.oschina.net/alarm1673/blog/741192

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值