上节介绍到 使用Class类的getResource("").getPath()获取当前.class文件所在的路径,存在中文乱码问题
下面几种方式会解决乱码问题:
- 第一种方式:
URL url=test.class.getResource("");
System.out.println("不乱码方式一:【"+URLDecoder.decode(url.getPath(), "UTF-8")+"】");
- 第二种方式:
URI uri=test.class.getResource("").toURI();//需要抛异常
System.out.println("不乱码方式二:【"+uri.getPath()+"】");
测试代码:
package com.test; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; public class test { public static void main(String[] args) throws URISyntaxException, UnsupportedEncodingException { String path1=test.class.getResource("").getPath(); System.out.println("中文乱码方:【"+path1+"】"); URL url=test.class.getResource(""); System.out.println("不乱码方式一:【"+URLDecoder.decode(url.getPath(), "UTF-8")+"】"); URI uri=test.class.getResource("").toURI();//需要抛异常 System.out.println("不乱码方式二:【"+uri.getPath()+"】"); System.out.println("-------------------------------------------------------"); URI uri1=test.class.getResource(".").toURI(); System.out.println("当前目录:【"+uri1.getPath()+"】"); URI uri2=test.class.getResource("..").toURI(); System.out.println("上层目录:【"+uri2.getPath()+"】"); URI uri3=test.class.getResource("/").toURI(); System.out.println("class文件存放目录:【"+uri3.getPath()+"】"); URI uri4=test.class.getResource("123.txt").toURI(); System.out.println("当前目录下123.txt文件的路径:【"+uri4.getPath()+"】"); } }
项目结构:
项目和打成的jar包存放路径:
eclipse和jar包运行结果:
对其中原理没有深入研究过,从运行结果来看,建议使用第一种方式; 或者之前介绍的 new file("").getCanonicalPath() 或者System.getProperty("user.dir")