Java中加载文件的几种方式
2020/2/2 5:03:18
本文主要是介绍Java中加载文件的几种方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在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根目录进行查找的。
这篇关于Java中加载文件的几种方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28AI给的和自己写的Python代码,都无法改变输入框的内容,替换也不行
- 2024-09-27Sentinel配置限流资料:新手入门教程
- 2024-09-27Sentinel配置限流资料详解
- 2024-09-27Sentinel限流资料:新手入门教程
- 2024-09-26Sentinel限流资料入门详解
- 2024-09-26Springboot框架资料:初学者入门教程
- 2024-09-26Springboot框架资料详解:新手入门教程
- 2024-09-26Springboot企业级开发资料:新手入门指南
- 2024-09-26SpringBoot企业级开发资料新手指南
- 2024-09-26Springboot微服务资料入门教程