Java读取resources中资源文件路径以及jar中文件无法读取如何解决

Java读取resources中资源文件路径以及jar中文件无法读取如何解决

本文讲解"Java读取resources中资源文件路径以及jar中文件无法读取怎么解决",希望能够解决相关问题。

Java读取resources中资源文件路径以及jar中文件无法读取的解决

问题描述

现象

作为一个刚开始学习java的新人,很多东西都是摸着石头过河,踩坑是常有的事。这不,今天我将maven管理的一个spring boot的WebAPP部署到服务器上,运行直接报错!纳尼!!!本地跑得好好的,一到服务器就出问题,关键是日志文件中的日志不全,无法马上定位到问题。好吧,一步一步排除问题吧!

定位

是不是windows与linux的区别?不是,我在windows上跑了一下打包后的代码,也出问题了,打包前没问题,打包后出问题了,包有毒!然后我开放了日志,一步一步调试(蛋疼啊),最终发现配置文件没有加载,路径出了问题。。。

前言

工程文件结构如下所示,目标是读取resources/python/kafka_producer.py文件

Java读取resources中资源文件路径以及jar中文件无法读取如何解决

1、本地运行读取资源文件

采用getResource进行读取:

URL urlPath = this.getClass().getResource("/python/kafka_producer.py");
String execStr = String.format("python %s", urlPath.getPath().substring(1));

它是在target文件中读取,这时文件是我们熟悉的文件。正常读取,运行。

2、读取jar包中的文件信息

InputStream is=this.getClass().getResourceAsStream("/python/kafka_producer.py");
BufferedReader br1=new BufferedReader(new InputStreamReader(is));
String s1="";
while((s1=br1.readLine())!=null)
	   System.out.println(s1);

如果你需要运行脚本文件,这时是不能直接通过路径获取的,具体可以看博客点击。你需要重新将流写入文件中,在运行,当然,也可以打war包,不用jar包。如果读取配置文件有一下两种方式:

InputStream in = this.getClass().getResourceAsStream("/properties/basecom.properties");
Properties properties = new Properties();
properties.load(in);
properties.getProperty("property_name")

或者

    InputStream xmlFile = this.getClass().getResourceAsStream("/jdbcType.xml");
	Document document = xmlReader.read(xmlFile);
	Element xmlRoot = document.getRootElement();
	Element childElement = xmlRoot.element(dbType);
	List<Element> childElements = childElement.elements();
	for (Element child : childElements) {
	}

聊聊Java项目读取resources资源文件路径那点事 

在Java程序中读取resources资源下的文件,由于对Java结构了解不透彻,遇到很多坑。

正常在Java工程中读取某路径下的文件时,可以采用绝对路径和相对路径,绝对路径没什么好说的,相对路径,即相对于当前类的路径。在本地工程和服务器中读取文件的方式有所不同,以下图配置文件为例:

Java读取resources中资源文件路径以及jar中文件无法读取如何解决

1、本地读取资源文件

Java类中需要读取properties中的配置文件,可以采用文件(File)方式进行读取:

File file = new File("src/main/resources/properties/test.properties");
InputStream in = new FileInputStream(file);

注意:当在IDEA中运行(不部署在服务器上),可以读取到该文件;

原因:JavaWeb项目部署服务器中,会将项目打包成Jar包或者war包,此时就不会存在 src/main/resources 目录,JVM会在编译项目时,主动将 java文件编译成 class文件 和 resources 下的静态文件放在 target/classes目录下;

理解:Java文件只有编译成 class文件才会被JVM执行,本地执行时会,当前项目即为Java进程的工作空间,虽然class文件在target/classes目录下,但是target/classes不是class文件运行的目录,只是存放的目录,运行目录还是在IDEA的模块下,所以运行时会找到 src/main/resources 资源文件!

2、服务器(Tomcat)读取资源文件

当工程部署到Tomcat中时,按照上边方式,则会抛出异常:FileNotFoundException。

原因:Java工程打包部署到Tomcat中时,properties的路径变到顶层(classes下),这是由Maven工程结构决定的。

由Maven构建的web工程,主代码放在src/main/java路径下,资源放在src/main/resources路径下,当构建jar包 或 war包时,JVM虚拟机会自动编译java文件为class文件存放在 target/classes目录下,resource资源下的文件会原封不动的拷贝一份到 target/classes 目录下:

Java读取resources中资源文件路径以及jar中文件无法读取如何解决

方式一:此时读取资源文件时

采用流(Stream)的方式读取,并通过JDK中Properties类加载,可以方便的获取到配置文件中的信息:

InputStream in = this.getClass().getResourceAsStream("/properties/test.properties");
Properties properties = new Properties();
properties.load(in);
properties.getProperty("name");

重点理解:class.getResourceAStream() 与 class.getClassLoader().getResorceAsStream() 的区别

Java读取resources中资源文件路径以及jar中文件无法读取如何解决

1) InputStream inStream = PropertiesTest.class.getResourceAsStream("test.properties");
2) inStream = PropertiesTest.class.getResourceAsStream("/com/test/demo/test.properties")
3) inStream = PropertiesTest.class.getClassLoader().getResourceAsStream("com/test/demo/test.properties");

1)第一种和第二种方式采用 Class 对象去加载,第三种方式采用 ClassLoader 对象去加载资源文件,之所以 Class 可以加载资源文件,是因为 Class 类封装的 ClassLoader 的 getResourceAsStream() 方法,从 Class 类中的源码可以看出:

public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
 }

理由:之所以这样做无疑还是方便客户端的调用,省的每次获取ClassLoader才能加载资源文件的麻烦!

2).class 是获取当前类的 class 对象,getClassLoader()是获取当前的类加载器,什么是类加载器?简单点说,就是用来加载java类的,类加载器就是负责把class文件加载进内存中,并创建一个java.lang.Class类的一个实例,也就是class对象,并且每个类的类加载器都不相同,getResourceAsStream(path)是用来获取资源的,因为这是ClassLoader(类加载器)获取资源,而类加载器默认是从 classPath 下获取资源的,因为这下面有class文件。

所以这段代码总的意思是通过类加载器在 classPath 目录下获取资源,并且是以流的形式。我们知道在Java中所有的类都是通过加载器加载到虚拟机中的,而且类加载器之间存在父子关系,就是子知道父,父不知道子,这样不同的子加载的类型之间是无法访问的(虽然它们都被放在方法区中),所以在这里通过当前类的加载器来加载资源也就是保证是和类类型是同一个加载器加载的。

(3)class.getClassLoader().getResourceAsStream() 和 class.getResouceAsStream() 的区别

a)class.getClassLoader().getResourceAsStream(Stringname)默认从classpath中找文件(文件放在resources目录下),name不能带"/",否则会抛空指针。采用相对路径, "/"就相当于当前进程的根目录,即项目根目录;

inStream = PropertiesTest.class.getClassLoader().getResourceAsStream("com/test/demo/test.properties");

b)class.getResourceAsStream(String name) 是采用绝对路径,绝对路径是相对于 classpath 根目录的路径,"/" 就代表着 classpath,所以 name 属性需要前面加上 "/";

inStream = PropertiesTest.class.getResourceAsStream("/com/test/demo/test.properties")

方式二:采用Spring注解

如果工程中使用Spring,可以通过注解的方式获取配置信息,但需要将配置文件放到Spring配置文件中扫描后,才能将配置信息放入上下文。

 <context:component-scan base-package="com.xxxx.service"/>
 <context:property-placeholder location="classpath:properties/xxx.properties" ignore-unresolvable="true"/>

然后在程序中可以使用 @Value进行获取properties文件中的属性值,如下:

 @Value("${xxxt.server}")
 private static String serverUrl;

方式三:采用Spring配置

也可以在Spring配置文件中读取属性值,赋予类成员变量

<?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
      <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="location" value="classpath:properties/xxx.properties"/>
      </bean>
     <bean id="service" class="com.xxxx.service.ServiceImpl">         <property name="serverUrl" value="${xxxt.server}" />
     </bean>
 </beans>

重点:SpringBoot项目启动后,动态的读取类路径下文件数据

InputStream inputStream = EncryptUtil.class.getResourceAsStream("/HelloServiceEncryptFile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
// 获取类路径下的文件路径
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists()) {
   path = new File("");
}
log.info("path = {}", path.getAbsolutePath());
File upload = new File(path.getAbsolutePath(), "com/study/service");
if (!upload.exists()) {
    upload.mkdirs();
}
FileOutputStream fos = new FileOutputStream(upload.getAbsolutePath() + File.separator + "hello.txt");
IoUtil.copy(inputStream, fos);
fos.close();
inputStream.close();

注意:此时我想读取 jar 包中根路径下的 HelloServiceEncryptFile.txt 文件,然后重新写入到根路径下的 com.study/service 路径下!

posted @ 2024-03-14 11:28  CharyGao  阅读(34)  评论(0编辑  收藏  举报