readFile

来源:互联网 发布:淘宝如何拍下商品 编辑:程序博客网 时间:2024/05/01 07:48

    public static void readFile() {
        // 行数
        int line = 0;
        // "|"分隔符所在index
        int seq = 0;
        // 报文key所在序号 [0,1,2..n]
        int keyNum = 0;
       
        ArrayList innerList = new ArrayList(); // innerList长度不定
        ArrayList list = new ArrayList();

        String path = "e://test.txt";
        FileReader fr = null;
        try {
            fr = new FileReader(path); //建立FileReader对象,并实例化为fr
        } catch (FileNotFoundException ex) {
        }
        BufferedReader br = new BufferedReader(fr); //建立BufferedReader对象,并实例化为br
        String lineContent = null;
        try {
            lineContent = br.readLine(); //从文件读取一行字符串
        } catch (IOException ex1) {
        }
        //判断读取到的字符串是否不为空
        while (lineContent != null) {
            line++;
            if (!(lineContent.startsWith("|") && lineContent.endsWith("|") && lineContent.length() > 2)) {
                System.out.println("第" + line + "行数据无效!");
                // 该行非法,跳至下一行
                try {
                    lineContent = br.readLine();
                } catch (IOException ex4) {
                }
                continue;               
            }
            System.out.println("正在读取第" + line + "行数据...");
            lineContent = lineContent.substring(1, lineContent.length());
           
            // 以下为内循环部分
            while (lineContent.length() > 0) {
                seq = lineContent.indexOf("|");
                innerList.add(lineContent.substring(0, seq));
                if (lineContent.length() == seq + 1) {
                    // 已读到行末"|"处,跳出搬循环
                    list.add(innerList.clone());
                    innerList.clear();
                    System.out.println("第" + line + "行读取完毕!");
                    break;
                }
                lineContent = lineContent.substring(seq + 1, lineContent.length());
            }
         
            try {
                lineContent = br.readLine(); //从文件中继续读取一行数据
            } catch (IOException ex3) {
            }
        }
        try {
            br.close(); //关闭BufferedReader对象
            fr.close(); //关闭文件
        } catch (IOException ex2) {
        }
        System.out.println("输出list: ");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
   
    /* test.txt 样式:
     |123|42|1232|asdfds|abddf|
     |df|aaaa|123,12ds|bbdd##|@#%$D|
     |123123133|!@#@!#|abc|adf123|bv,$#^$%|
     |basdfd|2006|04|00|123213|adfsd|123213123|1|123123|afadf|132|2006-09-01|123123123|1.25|444.12|0.12|6000.00|       
    */