java获取文件路径的方法

xiaoxiao2021-02-28  118

红色字体为转载者加注的。 第一种:  File f = new File(this.getClass().getResource("/").getPath());  System.out.println(f);  结果:  C:\Documents and Settings\Administrator\workspace\projectName\bin  获取当前类的所在工程路径; 只显示到class所在的路径,而不包含package的路径,比如你在工程里设置编译后的文件保存在bin下,则这里只显示到bin 如果不加“/”  File f = new File(this.getClass().getResource("").getPath());  System.out.println(f);  结果:  C:\Documents and Settings\Administrator\workspace\projectName\bin\com\test  获取当前类的绝对路径; 这个路径是编译后的class文件所在的路径,路径里包含了package的结构比如/com/test 第二种:  File directory = new File("");//参数为空  String courseFile = directory.getCanonicalPath() ;  System.out.println(courseFile);  结果:  C:\Documents and Settings\Administrator\workspace\projectName  获取当前类的所在工程路径;  第三种:  URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt");  System.out.println(xmlpath);  结果:  file:/C:/Documents and Settings/Administrator/workspace/projectName/bin/selected.txt  获取当前工程src目录下selected.txt文件的路径  第四种:  System.out.println(System.getProperty("user.dir"));  结果:  C:\Documents and Settings\Administrator\workspace\projectName  获取当前工程路径; 只显示到你的工程名,如果你的工程是executable jar,而且要想把config文件和你的jar放在同级目录,则可以用这个方法。 第五种:  System.out.println( System.getProperty("java.class.path"));  结果:  C:\Documents and Settings\Administrator\workspace\projectName\bin  获取当前工程路径
转载请注明原文地址: https://www.6miu.com/read-59562.html

最新回复(0)