Java 获取文件的绝对路径

tech2022-10-27  106

Java 获取文件的绝对路径

使用ClassLoader 类加载器 Properties pro = new Properties(); //获取src路径下的文件的方式--->ClassLoader 类加载器 ClassLoader classLoader = test.class.getClassLoader(); URL resource = classLoader.getResource("jdbc.properties"); String path = resource.getPath();

代码演示:

//获取类加载的根路径 D:\git\daotie\daotie\target\classes File path = new File(test.getClass().getResource("/").getPath()); // 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录 D:\git\daotie\daotie\target\classes\my File path = new File(test.getClass().getResource("").getPath()); // 第二种:获取项目路径 D:\git\daotie\daotie File directory = new File("");// 参数为空 String courseFile = directory.getCanonicalPath(); // 第三种: file:/D:/git/daotie/daotie/target/classes/ URL xmlpath = test.getClass().getClassLoader().getResource(""); // 第四种: D:\git\daotie\daotie System.out.println("path:" +System.getProperty("user.dir")); /* * 结果: C:\Documents and Settings\Administrator\workspace\projectName * 获取当前工程路径 */ // 第五种: 获取所有的类路径 包括jar包的路径 System.out.println("path: "+System.getProperty("java.class.path").split(";")[0]); // 第六种: 获取项目路径 D:/git/daotie/daotie.target/classes/ System.out.println("path: "+Thread.currentThread().getContentClassLoader().getResource("").getPath()); //第七种 表示到项目的根目录下, 要是想到目录下的子文件夹,修改"/"即可 String path7 = request.getSession().getServletContext().getRealPath("/")); } }
最新回复(0)