java 加载文件_Java中加载文件的几种方式

本文详细介绍了在Java中加载外部文件的三种方法:文件IO方式、Class.getResourceAsStream和ClassLoader.getResourceAsStream。通过实例展示了各自读取文件的规则,如相对路径与绝对路径的起点,以及如何根据不同的路径读取classpath下的资源文件。
摘要由CSDN通过智能技术生成

在Java程序中加载外部文件有多中方式,每种方式也存在区别,本文将理清这些加载方式之间的区别。

文件IO方式

package org.xialei.example.resource;

import java.io.File;

import java.io.IOException;

public class Main {

public static void main(String[] args) throws IOException {

File file = new File("app.properties");

System.out.println(file.getAbsolutePath());

}

}

常见的读取方式,使用该方式读取文件时规则如下:

如果传入的是绝对路径,则以系统根目录作为绝对路径的起点。

如果传入的是相对路径,则以当前工作目录作为起点。

本例中,运行java命令的目录即为工作目录,app.properties从工作目录开始查找。

Class.getResourceAsStream

package org.xialei.example.resource;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

public class Main {

public static void main(String[] args) throws IOException {

try (InputStream is = Main.class.getResourceAsStream("app.properties")) {

Properties properties = new Properties();

properties.load(is);

System.out.println(properties.getProperty("name"));

}

}

}

使用该方式读取文件时规则如下:

如果传入的是相对路径,则以当前class所在的包作为起点。

如果传入的是绝对路径,则以classpath的根目录为起点。

Main.class.getResourceAsStream("app.properties") 会读取/org/xialei/example/resource/app.properties文件。

Main.class.getResourceAsStream("/app.properties")会读取"classpath:/app.properties"文件

ClassLoader.getResourceAsStream

package org.xialei.example.resource;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

public class Main {

public static void main(String[] args) throws IOException {

try (InputStream is = Main.class.getClassLoader().getResourceAsStream("org/xialei/example/resource/app.properties")) {

Properties properties = new Properties();

properties.load(is);

System.out.println(properties.getProperty("name"));

}

}

}

使用该方式时规则如下:

使用classpath根目录作为起点。

本例中,org/xialei/example/resource/app.properties就是从classpath根目录进行查找的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值