写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. 配intelliJ IDEA 过程

    1.安装svn 选项全选择,命令行执行要选择上2.安装java jdk 配jdk环境变量3.安装intelliJ IDEA 地址:http://idea.imsxm.com4.注册intelliJ I ...

  2. ztree框架使用问题汇总

    1.如何让用户只能点击页子节点 var setting = { callback: { beforeClick: zTreeBeforeClick } }; function zTreeBeforeC ...

  3. TOJ 4003 Next Permutation

    描述 It is an interesting exercise to write a program to print out all permutations of 1, 2, …, n. How ...

  4. Java学习第二十五天

    1:如何让Netbeans的东西Eclipse能访问. 在Eclipse中创建项目,把Netbeans项目的src下的东西给拿过来即可. 注意:修改项目编码为UTF-8 2:GUI(了解) (1)用户 ...

  5. linux服务器git pull/push时避免频繁输入账号密码

    1.先cd到根目录,执行git config --global credential.helper store命令 [root@iZ25mi9h7ayZ ~]# git config --global ...

  6. 关于GBK、GB2312、UTF8之间的区别

    UTF-8:Unicode Transformation Format-8bit,允许含BOM,但通常不含BOM.是用以解决国际上字符的一种多字节编码,它对英文使用8位(即一个字节),中文使用24为( ...

  7. node.js发邮件

    在node上使用第三方类库(nodemailer)发邮件是一件很esay的事情:) app.js   以QQ邮箱为例 var nodemailer = require('nodemailer'); v ...

  8. android aidl通信 RemoteCallbackList客户端注册回调

    RemoteCallbackList 声明 public class RemoteCallbackList<E extends IInterface> 情况 在AIDL中客户端向服务端注册 ...

  9. artDialog组件应用学习(三)

    一.可以加载url的对话框 预览: 对话框编写代码 //弹出一个对话框,加载页面 function OpenBox(url, title, width, height) { seajs.use(['j ...

  10. ActiveReport报表更改连接字符串及参数

    PageReport pr = new PageReport (new FileInfo("报表路径")); //报表路径如../Order/OrderSale.rdlx if(p ...