• 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
  • 相关阅读:
    把 Maven 提交到项目?Maven Wrapper的使用与好处
    模型部署入门教程(六):实现 PyTorch-ONNX 精度对齐工具
    产品思维训练 | 如何有效提高问答网站中的问题回复率?
    没有虚拟DOM版本的vue(Vue Vapor)
    记一次接口优化操作
    Go内存分配
    百度网盘svip白嫖永久手机2024最新教程
    思腾云计算
    记录 Maven 版本覆盖 Bug 的解决过程
    18--Elasticsearch
  • 原文地址:https://blog.csdn.net/baidu_35805755/article/details/126251351