• java/获取路径user.dir和获取资源getResourceAsStream()


    总结

    获取路径:获取的是项目目录, System.getProperty("user.dir"), file.getCanonicalFile()
    获取资源:获取的是resources目录下的资源, class.getResourceAsStream("/xcrj-resources.txt"), class.getClassLoader().getResourceAsStream("xcrj-resources.txt")

    代码

    在这里插入图片描述

    package com.xcrj.path;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.charset.Charset;
    
    public class PathMain {
    
        public static void main(String[] args) throws IOException {
            // G:\micro-service\springbootbasic
            System.out.println(System.getProperty("user.dir"));
    
            // 设置为当前文件夹
            File file = new File("");
            // 标准路径,G:\micro-service\springbootbasic
            System.out.println(file.getCanonicalFile());
            // 绝对路径,G:\micro-service\springbootbasic
            System.out.println(file.getAbsolutePath());
            // 类的绝对路径,/G:/micro-service/springbootbasic/target/classes/
            System.out.println(PathMain.class.getResource("/").getPath());
    
            // resources/xcrj-resources.txt
            InputStream is = PathMain.class.getResourceAsStream("/xcrj-resources.txt");
            byte[] buf = new byte[is.available()];
            is.read(buf);
            System.out.println(new String(buf, Charset.forName("UTF-8")));
    
            // resources/xcrj-resources.txt
            InputStream is1 = PathMain.class.getClassLoader().getResourceAsStream("xcrj-resources.txt");
            byte[] buf2 = new byte[is1.available()];
            is1.read(buf2);
            System.out.println(new String(buf2, Charset.forName("UTF-8")));
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    BGP 的团体属性
    Ceph入门到精通-centos8 install brctl
    $refs不是响应式的
    RStudio学习笔记(一)
    xunhuan Jacobi method SVD
    用C++11 make_shared替代shared_ptr
    什么是视频剪辑SDK?
    Vue3响应式助你轻松实现国际化
    ASP.NET Core 6框架揭秘实例演示[24]:中间件的多种定义方式
    NLP之BM25:BM25算法的简介、相关库、案例应用之详细攻略
  • 原文地址:https://blog.csdn.net/baidu_35805755/article/details/126251351