java获取项目路径中文乱码

以下内容转自:http://blog.csdn.net/dream_broken/article/details/31762807#

  项目的文件名称推荐都是英文名称,但是有时不可避免使用了中文,获取项目路径是有可能会出现乱码,下面给出eclipse下获取路径的几种方法。

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.fei;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URI;  
  5. import java.net.URL;  
  6. import java.net.URLDecoder;  
  7.   
  8. public class Test01 {  
  9.   
  10.     public static void main(String[] args) {  
  11.         getPathMethod01();  
  12.         getPathMethod02();  
  13.         getPathMethod03();  
  14.         getPathMethod04();  
  15.     }  
  16.     private static String getPathMethod01(){  
  17.         String p = System.getProperty("user.dir");  
  18.         System.out.println("方法一路径:"+p);  
  19.         return p;  
  20.     }  
  21.       
  22.     private static String getPathMethod02(){  
  23.         URL url= Test01.class.getResource("");  
  24.         String p = url.getPath();  
  25.         System.out.println("方法二路径:"+p);  
  26.         try {  
  27.             System.out.println("方法二解码路径:"+URLDecoder.decode(p, "UTF-8"));  
  28.         } catch (UnsupportedEncodingException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.         return p;  
  32.     }  
  33.       
  34.     private static String getPathMethod03(){  
  35.         URL url= Test01.class.getResource("/");  
  36.         String p = url.getPath();  
  37.         System.out.println("方法三路径:"+p);  
  38.         try {  
  39.             System.out.println("方法三解码路径:"+URLDecoder.decode(p, "UTF-8"));  
  40.         } catch (UnsupportedEncodingException e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.         return p;  
  44.     }  
  45.     private static String getPathMethod04(){  
  46.         try {  
  47.             URI uri = Test01.class.getResource("/").toURI();  
  48.             String p = uri.getPath();  
  49.             System.out.println("方法四路径:"+p);  
  50.             return p;  
  51.         } catch (Exception e) {  
  52.             e.printStackTrace();  
  53.             throw new RuntimeException(e);  
  54.         }  
  55.     }  
  56. }  


运行结果:

 

方法一路径: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")即可解码。

 

    推荐使用方法四。

posted on 2017-05-13 19:30  傻瓜乐园  阅读(830)  评论(0)    收藏  举报

导航