Java中加载文件的几种方式

栏目: IT技术 · 发布时间: 6年前

内容简介:在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中加载文件的几种方式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

打造有吸引力的学习型社群

打造有吸引力的学习型社群

苏平、田士杰、吕守玉 / 机械工业出版社 / 45.00元

本书首先对社群的定位、准备和吸引粉丝方面等做了饶有趣味的介绍,从社群黏度的提升、社群知识的迭代与转化和社群的持续发展等多个角度入手,对学习型社群的运营手段、运营模式、运营规律和运营经验等进行了全方位剖析。从中国培训师沙龙这个公益社群近十年成功运营的经验中,为如何经营好学习型社群总结出了一套系统性的、具有实操价值的方法。并以此为基础,扩展到知识管理、团队管理、内容IP等领域,为有致于社团建设以及优质......一起来看看 《打造有吸引力的学习型社群》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具