boot中jar包部署的方式读取classes下的文件

来源:互联网 发布:天地诸神光翼进阶数据 编辑:程序博客网 时间:2024/06/05 03:24
下面的new File(String url)的方式在window中可以找到路径,但是单独部署jar文件时,获取到的URL路径是带有jar的
        String infile =  this.getClass().getClassLoader().getResource("").getFile()+"malls.json";        StringBuffer sb = new StringBuffer() ;        BufferedReader br = null ;        try {            br = new BufferedReader(new FileReader(infile)) ;            String s=null ;            while((s=br.readLine()) !=null){                sb.append(s) ;            }            br.close();        } catch (FileNotFoundException e) {            log.error("FileNotFoundException:"+e);        } catch (IOException e) {            log.error("IOException:"+e);        }finally {            if(br !=null){                try {                    br.close();                } catch (IOException e) {                    log.error("close br error:"+e);                }            }        }


正确的是写法是采用流的方式进行处理,同时读取流时设置编码utf-8

        InputStream stream = getClass().getClassLoader().getResourceAsStream("malls.json") ;//        log.info("infile:"+infile);        StringBuffer sb = new StringBuffer() ;        BufferedReader br = null ;        try {            br = new BufferedReader(new InputStreamReader(stream,"UTF-8")) ;            String s=null ;            while((s=br.readLine()) !=null){                sb.append(s) ;            }            br.close();        } catch (FileNotFoundException e) {            log.error("FileNotFoundException:"+e);        } catch (IOException e) {            log.error("IOException:"+e);        }finally {            if(br !=null){                try {                    br.close();                } catch (IOException e) {                    log.error("close br error:"+e);                }            }        }










阅读全文
0 0
原创粉丝点击