JAVA路径中空格问题

一、类路径
TestURL().class.getResource("").getPath()
TestURL.class.getResource("").getFile()获得的路径,不能被FileReader()FileWriter()直接应用。

例如:

String Path=this.getClass().getResource("/").toString 
String configPath=this.getClass().getResource("/").toString

原因是URL对于空格还有一些特殊字符进行了编码处理。

通过以上方式获取的路径会被处理其中的空格使用“20" 代替,解决办法如下:

String Path=this.getClass().getResource("/").toString().replaceAll("%20"," "); 

String configPath=this.getClass().getResource("/").toString().replaceAll("%20"," ");

以上可以解决空格问题 但是如果存在中文或者是就不可以了

或者

使用URLDecoder.decode(str,"UTF-8")解码,但是只能解决一部分,若路径中含有+,也是不能解决的,原因是URL并不是完全用URLEncoder.encode(str,"UTF-8")编码的,+号被解码后,却变成了空格。

或者:

以下可以解决所有问题:

TestURL().class.getResource("").toURI().getPath()

但是需要处理URISyntaxException异常,比较麻烦一些。

二、路径中的空格问题

windows批处理文件中如果,命令中含有空格,如下:
Java代码

1. setJAVA_JRE=D:/Program Files/tece2.1/jre 
   2. set CATALINA_HOME=D:/ProgramFiles/tece2.1/ 
   3. call   %CATALINA_HOME%bin/service  install 
   4. pause 

setJAVA_JRE=D:/Program Files/tece2.1/jre
set CATALINA_HOME=D:/Program Files/tece2.1/
call    %CATALINA_HOME%bin/service   install
pause

这样命令
Java代码

1.%CATALINA_HOME%bin/service 

%CATALINA_HOME%bin/service

中将含有空格,批处理文件将无法执行,需要在整个命令前后加双引号如下:

Java代码

1. setJAVA_JRE=D:/Program Files/tece2.1/jre 
   2. set CATALINA_HOME=D:/ProgramFiles/tece2.1/ 
   3. call  " %CATALINA_HOME%bin/service"  install 
  4. pause 

setJAVA_JRE=D:/Program Files/tece2.1/jre
set CATALINA_HOME=D:/Program Files/tece2.1/
call   "%CATALINA_HOME%bin/service"  install
pause

3、Runtime.getRuntime().exec()路基中含有空格,如下:

Java代码

1.Runtime.getRuntime().exec("cmd.exe /c D:\\Program Files\\tece2.1\\tececode\\updateprogram\\updateProgram.exe"); 

Runtime.getRuntime().exec("cmd.exe/c D:\\Program Files\\tece2.1\\tececode\\updateprogram\\updateProgram.exe");

这样讲无法执行,需要在空格的前后加上双引号,而不是在整个路径的前后加双引号,如下:
Java代码

1.Runtime.getRuntime().exec("cmd.exe /c D:\\Program\"\"Files\\tece2.1\\tececode\\updateprogram\\updateProgram.exe"); 

Runtime.getRuntime().exec("cmd.exe/c D:\\Program\"\"Files\\tece2.1\\tececode\\updateprogram\\updateProgram.exe");

或者使用替换方式:
Java代码

1. String  commandStr="cmd.exe /c"+"" +realPath.realTomcatPath.replace(" ", "\"\"");   

String  commandStr="cmd.exe /c"+"" +realPath.realTomcatPath.replace(" ", "\"\""); 

Java代码

1.Runtime.getRuntime().exec(commandStr); 

Runtime.getRuntime().exec(commandStr);

你可能感兴趣的:(Java)