Java中读取jar包中的文件

来源:互联网 发布:软件ac管理控制器 编辑:程序博客网 时间:2024/06/05 07:22

我的一个SpringBoot项目需要在应用启动时读取一个文件,并添加到数据库中,在这遇到了一个坑,就是在Idea 中,应用启动时可以正常读取这个文件,但应用打成jar包后直接运行就读取不到。

要读取的文件位于 /src/main/resources 目录下,其相对路径为/src/main/resources/data/schema.json.

究其原因,此时运行中的Java程序其实是在读取jar包中的文件,直接使用下面的方式是不行的:

常见的读取文件路径中的文件的写法:String path = this.getClass().getClassLoader().getResource(path).getPath();//文件内容直接转为String类型String input = FileUtils.readFileToString(new File(path), "UTF-8");

在Java中,如果应用打成jar包后,应用运行后需要读取本jar包之内的文件,正确的写法:

BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(path)));StringBuffer buffer = new StringBuffer();String line = "";while ((line = in.readLine()) != null){    buffer.append(line);}String input = buffer.toString();

附:InputStream,String,File相互转化方式
转自:https://www.cnblogs.com/cpcpc/archive/2011/07/08/2122996.html

1、String –> InputStream

InputStream String2InputStream(String str){    ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());   return stream;}

2、InputStream –> String

String inputStream2String(InputStream is){   BufferedReader in = new BufferedReader(new InputStreamReader(is));   StringBuffer buffer = new StringBuffer();   String line = "";   while ((line = in.readLine()) != null){     buffer.append(line);   }   return buffer.toString();}

今天从网上看到了另一种方法,特拿来分享

String all_content=null;try {    all_content = new String();    InputStream ins = 获取的输入流;    ByteArrayOutputStream outputstream = new ByteArrayOutputStream();    byte[] str_b = new byte[1024];    int i = -1;    while ((i=ins.read(str_b)) > 0) {       outputstream.write(str_b,0,i);    }    all_content = outputstream.toString(); } catch (Exception e) {    e.printStackTrace(); }

此两种方法上面一种更快,但是比较耗内存,后者速度慢,耗资源少

3、File –> InputStream

InputStream in = new InputStream(new FileInputStream(File));

4、InputStream –> File

public void inputstreamtofile(InputStream ins,File file){    OutputStream os = new FileOutputStream(file);    int bytesRead = 0;    byte[] buffer = new byte[8192];    while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {        os.write(buffer, 0, bytesRead);    }    os.close();    ins.close();}
原创粉丝点击