(1).Test.class.getResource("") 得到的是当前类FileTest.class文件的URI目录。不包括自己! (2).Test.class.getResource("/") 得到的是当前的classpath的绝对URI路径。 (3).Thread.currentThread().getContextClassLoader().getResource("")
Stringpath=CurrentFilePath.class .getProtectionDomain() .getCodeSource() .getLocation() .getPath(); // 解码URL编码的路径(处理空格和特殊字符) StringdecodedPath=URLDecoder.decode(path, StandardCharsets.UTF_8.toString()); FilecurrentFile=newFile(decodedPath); System.out.println("当前文件绝对路径: ...
使用try-catch块捕获异常:在调用getAbsolutePath()方法时,将其放在一个try-catch块中,以捕获任何可能的异常。这样可以帮助你查找到具体的错误。 使用File类的isFile()或isDirectory()方法:在调用getAbsolutePath()方法之前,可以使用isFile()或isDirectory()方法来检查路径是否是文件或目录,以确保获取到的是正确的绝...
(1).Test.class.getResource("") 得到的是当前类FileTest.class文件的URI目录。不包括自己! (2).Test.class.getResource("/") 得到的是当前的classpath的绝对URI路径。 (3).Thread.currentThread().getContextClassLoader().getResource("") 得到的也是当前ClassPath的绝对URI路径。 (4).Test.class.getClass...
(1)类的绝对路径:Class.class.getClass().getResource("/").getPath() 结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/ (2)得到工程的路径:System.getProperty("user.dir") 结果:D:/TEST 3.在Servlet中取得路径: (1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包...
getAbsolutePath():返回抽象路径名的绝对路径名字符串。public static void test1(){ File file1 = new File(".\\test1.txt");File file2 = new File("D:\\workspace\\test\\test1.txt");System.out.println("---默认相对路径:取得路径不同---");System.out.println(file1.getPath()...
StringabsolutePath=file.getAbsolutePath(); 1. 这里的absolutePath是一个字符串,用于存储文件的绝对路径。 步骤3:提取文件的名称 最后一步是提取文件的名称。一种常见的方法是使用字符串处理的方法,例如使用substring()和lastIndexOf()来提取文件名部分。
2.2、getAbsolutePath()返回的其实是user.dir+getPath()的内容,从上面看:D:\workspace\java_io\.\src\test.txt,D:\workspace\http://java_io\..\src\test.txt,可以得出。 2.3、getCanonicalPath()返回的就是标准的将符号完全解析的路径
getClass().getResource() 方法获得相对路径( 此方法在jar包中无效。返回的内容最后包含/)例如 项目在/D:/workspace/MainStream/Test 在javaProject中,getClass().getResource("/").getFile().toString() 返回:/D:/workspace/MainStream/Test/bin/ public String getCurrentPath(){ //取得根目录...
if(path !=null) { path = path.substring(5, path.indexOf("WEB-INF") + 8);//如果是windwos将5变成6 //System.out.println("current path :" + path); } return(path + fileName); } getClass().getResource() 方法获得相对路径(此方法在jar包中无效。返回的内容最后包含/) ...