• java解析文件


    遇到两个小坑:

    1、使用String.split,部分分隔符需要转义:https://www.cnblogs.com/mingforyou/archive/2013/09/03/3299569.html

    2、读取文件,报文件找不到:http://blog.51cto.com/632977922/1128981

    3、java.io.FileNotFoundException: file:/home/admin/trunner/scenarios/64124/63844/target/larkPerf.jar!/data/getGoodsCategory.txt (没有那个文件或目录)

    linux和windows文件夹分隔符不一样:

    this.getClass().getClassLoader().getResource("data").getPath() + File.separator + "getGoodsCategory.txt"
    public class FileUtils {
    
        public static List<String> file2List(String filePath) throws IOException {
            List<String> lines = new ArrayList();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            String line;
            while (null != (line=bufferedReader.readLine())){
                lines.add(line);
            }
            return lines;
        }
    
        /**
         * 解析文件,返回mapList
         * @param filePath
         * @return
         * @throws IOException
         */
        public static List file2MapList(String filePath) throws IOException {
            List list = file2List(filePath);
            List mapList = new ArrayList();
            List<String> line,head = null;
            for (int i=0; i<list.size(); i++){
                Map<String, String> tmpMap = new HashMap();
                //第一行为表头 (二狗,直接用excel或xml吧,解析得这么费劲)
                if (0 == i){
                    head = Arrays.asList(list.get(i).toString().split("\|"));
                    continue;
                }
                line = Arrays.asList(list.get(i).toString().split("\|"));
                for (int j=0;j<line.size(); j++){
                    tmpMap.put(head.get(j), line.get(j));
                }
                mapList.add(tmpMap);
            }
            return mapList;
        }
    
        @Test
        public void test(){
            try {
                List<String> list = file2List("D:\code\code-test\lark-perf\src\main\groovy\cn\com\ykse\perf\util\test.txt");
                System.out.println(list.get(0));
                List list1 = file2MapList("D:\code\code-test\lark-perf\src\main\groovy\cn\com\ykse\perf\util\test.txt");
                System.out.println(list1);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    

    =====2018-09-11补充=========
    第3点找不到文件,是打成jar包后运行报错。一个项目中编译运行||引用jar包读取文件,方式不一样
    引用jar包并读取该jar包文件时,应该用
    this.getClass().getResourceAsStream(fileName)
    详情参考:https://www.cnblogs.com/cn-coder/p/7089688.html

  • 相关阅读:
    C#引用类型详细剖析(转)
    wcf问题集锦
    Emgu CV 初试
    C#语言使用习惯
    多线程和消息机制
    ArrayAdapter
    SimpleAdapter
    删除对话框
    HTML制作个人简历
    冒泡排序
  • 原文地址:https://www.cnblogs.com/dannyyao/p/9462728.html
Copyright © 2020-2023  润新知