Java processing method for reading file path spaces, “+” and Chinese
Sometimes the file is read in Java code. If the path of the file contains spaces ”+In case of "No. or Chinese", because these special characters will be encoded and translated, the error that the file is not found will be reported. In case of this error, we need to decode the encoded path in order to correctly find the file. The main solutions are as follows:
resolvent
1. Substitution method
For example, if there are spaces in the file path, it will be translated into "% 20", so you can use string replacement to convert "% 20" into spaces, so that you can correctly find the file. This is such a violent and low-level processing method that most experienced developers will not adopt it?
2. Use urlcoder Decode (STR, ENC)
If the spaces and Chinese are translated, you can use urldecoder Decode method, but this method can not decode the "+" sign in the path correctly because urlcoder If a plus sign is found inside the decode method, it will be converted to a space:
3. Universal method, using touri () getPath()
Touri () will encode the string according to its own rules, and then it can decode it automatically, so you don't have to care about these things. You can look at its source code by yourself.
demonstration:
The web project is deployed in a Tomcat. The path is: "D: \ program files \ Java \ apache-tomcat-6.0 26”
1. String contains spaces:
It can be seen from the screenshot that the spaces in the path have been converted to "% 20". If the path containing spaces is not decoded, the file cannot be obtained directly; If the second and third methods above are used, the file can be obtained correctly.
2. The path contains "+"
As can be seen from the above figure, if the path contains a "+" sign, the second method fails, but the third method is still effective. Therefore, it is better to use the third method at ordinary times. In addition, the method described above is also applicable if deployed under Linux.
The above processing method of Java reading file path spaces, "+" and Chinese is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.