写Java程序时会经常从classpath下读取文件,是时候该整理一下了,并在不断深入的过程中,陆续补充上。

现在Java project 都以maven项目居多, 比如像下面这样的一个项目结构:

编译后的class文件都到了target目录,如下面的结构:

看代码:

import java.io.File;
import java.net.URL; public class Poem {
public static void main(String[] args) { Poem poem = new Poem();
poem.getFile("extObj.txt");
} private void getFile(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
/**
getResource()方法会去classpath下找这个文件,获取到url resource, 得到这个资源后,调用url.getFile获取到 文件 的绝对路径
*/
URL url = classLoader.getResource(fileName);
/**
* url.getFile() 得到这个文件的绝对路径
*/
System.out.println(url.getFile());
File file = new File(url.getFile());
System.out.println(file.exists());
}
}

通过上面这种方式就可以获取到这个文件资源。
在一个static method 里可以直接通过类的ClassLoader对象获取文件资源。

URL url = Poem.class.getClassLoader().getResource("extObj.txt");
File file = new File(url.getFile());
// 直接获取到输入流
// fileName 就是resources里的文件名
InputStream in = Poem.class.getClassLoader().getResourceAsStream(fileName);

综上述,类里的getClassLoader去寻找fileName都是从classpath去找的,毕竟是ClassLoader嘛。

如果一个包里面有一个配置文件,那该怎么获取呢? 如图:

第一个dbconfig.properties在类package下,第二个dbconfig.properties在resources目录下,
那怎么获取到package下的dbconfig properties文件呢?
here goes code:

package com.getfilefromclasspath;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; public class ClassLoaderDemo {
public static void main(String[] args) throws IOException {
ClassLoaderDemo demo = new ClassLoaderDemo();
demo.loadProperties(); } public void loadProperties() throws IOException {
InputStream input = null;
try
{
/**
/dbconfig.properties 绝对路径, 取到的文件是classpath下的
resources/dbconfig.properties 相对路径 获取文件流
*/
// 获取到classpath下的文件
input = Class.forName(ClassLoaderDemo.class.getName()).getResourceAsStream("/dbconfig.properties");
// 获取到package下的文件
// input = Class.forName(ClassLoaderDemo.class.getName()).getResourceAsStream("resources/dbconfig.properties");
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
printProperties(input);
} private void printProperties(InputStream input) throws IOException
{
Properties properties = new Properties();
properties.load(input);
System.out.println(properties.getProperty("username"));
}
}

不使用Class.forName(), 通过具体对象获取到Class对象:

//also can be this way:
input = this.getClass().getResourceAsStream("resources/dbconfig.properties"); // 对应package下的文件
input = this.getClass().getResourceAsStream("/dbconfig.properties"); // 对应resources下的文件

Class对象还有getResource() 的方法去获取文件资源,使用规则和上面的一样。

maven项目还要注意一点,maven 的compiler插件在编译时是不会将package下的文本文件给编译到target下的,
下图是我在用mybatis框架的时候将xml的mapper给放到package编译后的效果:

这个得在pom.xml加对应的配置(这是在使用mybatis时遇到的坑):

<build>
<finalName>java-io</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<!--properties的配置文件会和编译后的class文件放在一起-->
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<!--加载配置的资源-->
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

Java读取classpath下的文件的更多相关文章

  1. java读取classpath下properties文件注意事项

    1.properties文件在classpath根路径下读取方式 Properties properties = new Properties(); properties.load(BlogIndex ...

  2. 读取ClassPath下resource文件的正确姿势

    1.前言 为什么要写这篇文章?身为Java程序员你有没有过每次需要读取 ClassPath 下的资源文件的时候,都要去百度一下,然后看到下面的这种答案: Thread.currentThread(). ...

  3. 【转】SpringBoot——web项目下读取classpath下的文件心得

    在读取springBoot+gradle构建的项目时,如果使用传统的FileInputStream读取文件流或者ResourceUtils工具类的方式,都会失败,下面解释原因: 一.读取文件的三种方式 ...

  4. 解决:java 读取 resources 下面的 json 文件

    前言:java 读取 工程下的配置文件,文件类型为 json(*.json),记录一下始终读取不到 json 文件的坑.maven项目 直接上工具类代码 package com.yule.compon ...

  5. java 获取classpath下文件多种方式

    java 获取classpath下文件多种方式 一:properties下配置 在resources下定义server.properties register.jks.path=classpath\: ...

  6. SpringBoot项目构建成jar运行后,如何正确读取resource下的文件

    SpringBoot项目构建成jar运行后,如何正确读取resource下的文件 不管你使用的是SpringBoot 1.x还是SpringBoot2.x,在开Dev环境中使用eclipse.IEAD ...

  7. Java读取Level-1行情dbf文件极致优化(3)

    最近架构一个项目,实现行情的接入和分发,需要达到极致的低时延特性,这对于证券系统是非常重要的.接入的行情源是可以配置,既可以是Level-1,也可以是Level-2或其他第三方的源.虽然Level-1 ...

  8. Java读取Level-1行情dbf文件极致优化(2)

    最近架构一个项目,实现行情的接入和分发,需要达到极致的低时延特性,这对于证券系统是非常重要的.接入的行情源是可以配置,既可以是Level-1,也可以是Level-2或其他第三方的源.虽然Level-1 ...

  9. Java遍历目录下全部文件并替换指定字符串

    应用场景:比方有一个深层次的文件目录结构,如:javaAPI 每一个文件中面都有同样的内容,而我们要统一改动为其它内容.上千个文件假设一个个改动显得太不明智. import java.io.Buffe ...

随机推荐

  1. 15019:Only the instance admin may alter the PermSize attribute

    15019:Only the instance admin may alter the PermSize attribute TimesTen提示空间不足,增加空间重启后提示15019:Only th ...

  2. 委托delegate 泛型委托action<> 返回值泛型委托Func<> 匿名方法 lambda表达式 的理解

    1.使用简单委托 namespace 简单委托 { class Program { //委托方法签名 delegate void MyBookDel(int a); //定义委托 static MyB ...

  3. mysql 索引、查询优化

    查询计划Explain mysql查询过程中,如若想了解当前sql的执行计划,可以通过explain your_sql的方式查看,具体可以参考mysql官方解释:https://dev.mysql.c ...

  4. Java Collection.Set

    package 集合; /** * Set不包含重复元素 存储顺序和取出数据不一样 * * HashSet:它不保证set的迭代顺序,特别是它不保证该顺序恒久不变 * 底层是哈希表结构的 * Link ...

  5. Nginx的各种报错总结

    1.Nginx安装过程报错 错误一:软件依赖包未正确安装问题---PCRE依赖包没有安装 ./configure: error: the HTTP rewrite module requires th ...

  6. artDialog组件应用学习(一)

    个人觉得artDialog是一组很不错的对话框组件.写的是artDialog_v6应用. 官方称其兼容性测试通过:IE6~IE11.Chrome.Firefox.Safari.Opera. 官网:ht ...

  7. scss-@mixin

    @mixin指令用于定义混入,它包括任选的变量和参数中的mixin名称后. scss简单示例: @mixin style { .cont{ color: #77C1EF; } } @include s ...

  8. JavaScript彻底搞懂apply和call方法

    彻底搞懂JavaScript中的apply和call方法 call和apply都是为了改变某个函数运行的context上下文而存在的,即为了改变函数体内部this的指向.因为JavaScript的函数 ...

  9. Latest SoC

    From: http://laoyaoba.com/ss6/html/68/n-505768.html 2014年国产ARM SoC芯片巡礼(上) 关注“集微网”,微信点播新闻.随要随有 来源: &l ...

  10. PHP header() session_start() 函数前为什么不能有输出?

    前阵面试遇到的问题,当时没答上来,后来查了些资料,仍未得到答案.今天研究HTTP请求,终于知道了答案. HTTP 函数允许在其他输出被发送之前,对由 Web 服务器发送到浏览器的信息进行操作. HTT ...