java获取项目路径中文乱码
以下内容转自:http://blog.csdn.net/dream_broken/article/details/31762807#
项目的文件名称推荐都是英文名称,但是有时不可避免使用了中文,获取项目路径是有可能会出现乱码,下面给出eclipse下获取路径的几种方法。
- package com.fei;
- import java.io.UnsupportedEncodingException;
- import java.net.URI;
- import java.net.URL;
- import java.net.URLDecoder;
- public class Test01 {
- public static void main(String[] args) {
- getPathMethod01();
- getPathMethod02();
- getPathMethod03();
- getPathMethod04();
- }
- private static String getPathMethod01(){
- String p = System.getProperty("user.dir");
- System.out.println("方法一路径:"+p);
- return p;
- }
- private static String getPathMethod02(){
- URL url= Test01.class.getResource("");
- String p = url.getPath();
- System.out.println("方法二路径:"+p);
- try {
- System.out.println("方法二解码路径:"+URLDecoder.decode(p, "UTF-8"));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return p;
- }
- private static String getPathMethod03(){
- URL url= Test01.class.getResource("/");
- String p = url.getPath();
- System.out.println("方法三路径:"+p);
- try {
- System.out.println("方法三解码路径:"+URLDecoder.decode(p, "UTF-8"));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return p;
- }
- private static String getPathMethod04(){
- try {
- URI uri = Test01.class.getResource("/").toURI();
- String p = uri.getPath();
- System.out.println("方法四路径:"+p);
- return p;
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
- }
运行结果:
方法一路径:E:\test\test04练 习
方法二路径:/E:/test/test04%e7%bb%83%20%20%e4%b9%a0/bin/com/fei/
方法二解码路径:/E:/test/test04练 习/bin/com/fei/
方法三路径:/E:/test/test04%e7%bb%83%20%20%e4%b9%a0/bin/
方法三解码路径:/E:/test/test04练 习/bin/
方法四路径:/E:/test/test04练 习/bin/
通过看代码和运行结果可以看到,用url.getPath()获取到的路径被utf-8编码了,用URLDecoder.decode(p, "UTF-8")即可解码。
推荐使用方法四。
浙公网安备 33010602011771号