开发者

java获取文件路径所有方式的详细介绍

目录
  • 前言
  • 一、使用System属性获取路径
    • 1. 获取当前工作目录
    • 2. 获取用户主目录
    • 3. 获取 Java 安装目录
  • 二、使用File类获取路径
    • 1. 获取文件的绝对路径
    • 2. 获取规范路径(解析符号链接)
    • 3. 获取父目录路径
  • 三、使用ClassLoader获取资源路径
    • 1. 使用Class.getResource()获取类路径下的资源
    • 2. 使用ClassLoader.getResource()获取资源
    • 3. 解码 URL 路径中的特殊字符
  • 四、使用Paths类(Java 7+)
    • 1. 获取当前工作目录的绝对路径
    • 2. 拼接路径
  • 五、使用URI获取路径
    • 1. 将文件转换为 URI
    • 2. 使用 URI 加载资源
  • 六、Web 应用中的路径获取
    • 1. JSP 中获取路径
    • 2. Servlet 中获取路径
  • 七、Spring Boot 中获取资源路径
    • 1. 使用getResourceAsStream读取资源
  • 八、其他方式
    • 1. 使用ProtectionDomain获取类文件路径
    • 2. 使用File.separator处理跨平台路径
  • 九、注意事项
    • 总结

      前言

      在 Java 中,获取文件路径是开发中常见的需求,尤其是在处理资源文件、配置文件或动态路径拼接时。以下是 Java 获取文件路径的所有方式 的详细介绍:

      一、使用System属性获取路径

      1. 获取当前工作目录

      String currentDir = System.getProperty("user.dir");
      System.out.println("当前工作目录: " + currentDir);编程客栈
      
      • 适用场景:获取 Java 程序的启动目录(即命令行运行程序的位置)。

      2. 获取用户主目录

      String userHome = System.getProperty("user.home");
      System.out.println("用户主目录: " + userHome);
      
      • 适用场景:获取操作系统用户的主目录(如 Windows 的 C:\Users\用户名)。

      3. 获取 Java 安装目录

      String javaHome = System.getProperty("java.home");
      System.out.println("Java 安装目录: " + javaHome);
      
      • 适用场景:获取 Java 运行时的安装路径js

      二、使用File类获取路径

      1. 获取文件的绝对路径

      File file = new File("example.txt");
      String absolutePath = file.getAbsolutePath();
      System.out.println("绝对路径: " + absolutePath);
      
      • 适用场景:获取当前文件对象的绝对路径(基于当前工作目录)。

      2. 获取规范路径(解析符号链接)

      try {
          String canonicalPath = file.getCanonicalPath();
          System.out.println("规范路径: " + canonicalPath);
      } catch (IOETdQMGDFNWxception e) {
          e.printStackTrace();
      }
      
      • 适用场景:获取去除符号链接后的实际路径(如 ..~ 的解析)。

      3. 获取父目录路径

      String parentPath = file.getParent();
      System.out.println("父目录: " + parentPath);
      
      • 适用场景:获取文件的父目录路径(如 C:\project\srcC:\project\src\main.java 的父目录)。

      三、使用ClassLoader获取资源路径

      1. 使用Class.getResource()获取类路径下的资源

      URL resourceUrl = Demo.class.getResource("/config.properties");
      if (resourceUrl != null) {
          String resourcePath = resourceUrl.getPath();
          System.out.println("资源路径: " + resourcePath);
      }
      
      • 适用场景:获取类路径(src/main/resources)下的资源文件路径。
      • 注意:路径以 / 开头表示从类路径根目录开始查找。

      2. 使用ClassLoader.getResource()获取资源

      ClassLoader classLoader = Demo.class.getClassLoader();
      URL resourceUrl = classLoader.getResource("config.properties");
      if (编程resourceUrl != null) {
          String resourcePath = resourceUrl.getPath();
          System.out.println("资源路径: " + resourcePath);
      }
      
      • 适用场景:与 Class.getResource() 类似,但路径不以 / 开头。

      3. 解码 URL 路径中的特殊字符

      try {
          String decodedPath = URLDecoder.decode(resourceUrl.getPath(), "UTF-8");
          System.out.println("解码后路径: " + decodedPath);
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      
      • 适用场景:处理 URL 路径中的编码(如 %20 表示空格)。

      四、使用Paths类(Java 7+)

      1. 获取当前工作目录的绝对路径

      Path currentDir = Paths.get(".").toAbsolutePath();
      System.out.println("当前目录: " + currentDir);
      

      2. 拼接路径

      Path filePath = Paths.get(currentDir.toString(http://www.devze.com), "example.txt");
      System.out.println("文件路径: " + filePath);
      
      • 适用场景:跨平台路径拼接(自动适配 /\)。

      五、使用URI获取路径

      1. 将文件转换为 URI

      File file = new File("example.txt");
      URI uri = file.toURI();
      System.out.println("URI 路径: " + uri.getPath());
      

      2. 使用 URI 加载资源

      URL resourceUrl = Demo.class.getResource("/example.txt");
      URI resourceUri = resourceUrl.toURI();
      System.out.println("URI 路径: " + resourceUri);
      
      • 适用场景:处理网络资源或本地文件路径的统一标识。

      六、Web 应用中的路径获取

      1. jsP 中获取路径

      <%
          // 获取当前页面全路径
          String requestURI = request.getRequestURI();
          out.println("请求路径: " + requestURI);
      
          // 获取工程名
          String contextPath = request.getContextPath();
          out.println("工程名: " + contextPath);
      
          // 获取服务器上的物理路径
          String realPath = application.getRealPath("/");
          out.println("物理路径: " + realPath);
      %>
      

      2. Servlet 中获取路径

      // 获取工程目录
      String realPath = getServletContext().getRealPath("/");
      System.out.println("工程目录: " + realPath);
      
      // 获取请求地址
      String requestURL = request.getRequestURL().toString();
      System.out.println("请求地址: " + requestURL);
      

      七、Spring Boot 中获取资源路径

      1. 使用getResourceAsStream读取资源

      InputStream inputStream = getClass().getClassLoader().getResourceAsStream("config.properties");
      if (inputStream != null) {
          // 读取流内容
      }
      
      • 适用场景:资源嵌套在 JAR 包中时,无法直接获取文件路径,需通过输入流读取。

      八、其他方式

      1. 使用ProtectionDomain获取类文件路径

      URL classLocation = Demo.class.getProtectionDomain().getCodeSource().getLocation();
      String classPath = classLocation.getPath();
      System.out.println("类文件路径: " + classPath);
      
      • 适用场景:获取编译后的 .class 文件路径(如 JAR 包路径)。

      2. 使用File.separator处理跨平台路径

      String path = "D:" + File.separator + "test" + File.separator + "file.txt";
      System.out.println("跨平台路径: " + path);
      
      • 适用场景:手动拼接路径时确保兼容性(Windows 用 \,linux 用 /)。

      九、注意事项

      1. 资源在 JAR 包内时

        • 无法通过 getFile() 获取实际路径,需使用 getResourceAsStream() 读取流。
        • 示例:
          InputStream inputStream = getClass().getResourceAsStream("/config.properties");
          
      2. 路径编码问题

        • URL 路径可能包含编码(如 %20 表示空格),需使用 URLDecoder 解码。
      3. 相对路径与绝对路径

        • 相对路径基于当前工作目录(user.dir),绝对路径是完整路径。
      4. Web 应用与普通 Java 应用

        • Web 应用中路径通常基于 WebRootWEB-INF/classes
        • 普通 Java 应用中路径基于项目根目录或类路径。

      总结

      方法适用场景是否跨平台是否涉及 I/O
      System.getProperty获取系统属性路径
      File.getAbsolutePath获取文件绝对路径
      ClassLoader.getResource获取类路径资源
      Paths.get(...)跨平台路径拼接
      URI统一资源标识
      Web 应用中的 request获取 Web 请求路径
      getResourceAsStream读取 JAR 内资源

      根据具体需求选择合适的方法,确保路径处理的灵活性和兼容性。

      到此这篇关于java获取文件路径所有方式的文章就介绍到这了,更多相关java获取文件路径内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

      0

      上一篇:

      下一篇:

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      最新开发

      开发排行榜