The mutual conversion of URL and File in java

http://blog.csdn.net/linjx2004/article/details/5608909


First, I want to compare the difference between the two. URL is used for the network, so it has an obvious protocol, and it does not support Chinese and symbols very well. File is the file path in our usual system. It supports both Chinese and symbols, but there is no protocol. So, although both can represent file paths, they cannot be mixed.
Comparison of typical URL and File paths:
URL: file:/D:/my%20java/URL&FILE/%e5%9b%be%e7%89%87/tongji.jpg
File: D:/my java/URL&FILE/image /tongji.jpg
is actually one file.

Back to the topic:
This is the method I found under JDK5.0, which is not supported under JDK5.0:
URL to File:
URL url=...;
File file=new File(url.toURI);

File to URL:
File file =……;
URL url=file.toURL();

 

++++++++++++++++++++++++++++

Get the JAVA path, including the path other than CLASSPATH

Summarize some methods to get the JAVA path on the Internet:
  Note: If you start the program from ANT, this.getClass().getResource("") is rather strange, and you can use the JAVA command line to debug it directly. to be successful.
  
  Some methods to get the absolute path of classpath and current class Methods
  to get the path outside CLASSPATH:
  URL base = this.getClass().getResource(""); //Get the location of this class first, such as /home/popeye/ testjava/build/classes/net/
  String path = new File(base.getFile(), "../../../"+name).getCanonicalPath(); //You can get /home/popeye/testjava Below /name
  are some methods to get the classpath and the absolute path of the current class. You may need to use some of these methods to get the absolute path to the resource you need.
  1.FileTest.class.getResource("")
  gets the URI directory of the current class FileTest.class file. Not including myself!
  For example: file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/
  2.FileTest.class.getResource("/")
  gets the absolute URI path of the current classpath.
  For example: file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
  3.Thread.currentThread().getContextClassLoader().getResource("")
  is also the absolute URI path of the current ClassPath.
  For example: file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
  4.FileTest.class.getClassLoader().getResource("")
  is also the absolute URI path of the current ClassPath.
  For example: file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
  5.ClassLoader.getSystemResource("")
  also gets the absolute URI path of the current ClassPath.
  For example: file:/D:/java/eclipse32/workspace/jbpmtest3/bin/
  
I recommend using Thread.currentThread().getContextClassLoader().getResource("") to get the URI representation of the absolute path of the current classpath.
  In Web applications, we generally pass ServletContext.getRealPath("/" ) method to get the absolute path of the root directory of the web application. In this way, we only need to provide a path relative to the root directory of the web application to construct an absolute path for locating resources.
  be careful:
  1. Try not to use a relative path relative to the current user directory of System.getProperty("user.dir"). This is a ticking time bomb that could kill you at any time.   2. Try to use absolute path resources in the
  form of URI .
It can be easily converted to URI, URL, File objects.
  3. Try to use a relative path relative to the classpath. Do not use absolute paths. Using the public static URL getExtendResource(String relativePath) method of the ClassLoaderUtil class above has been able to locate resources at all locations using a relative path relative to the classpath.
  4. Never use hardcoded absolute paths. Because, we can use the getResource("") method of the ClassLoader class to get the absolute path of the current classpath.
  Using hardcoded absolute paths is completely unnecessary! It's sure to make you die ugly! Programs will not be portable!
  If you must specify an absolute path, then using a configuration file is also much better than hardcoding!
  Of course, I still recommend that you use the program to get the absolute path of the classpath to spell the absolute path of the resource.

===================================================== =============================

In the process of developing java programs, one of the things we often do is to obtain resources. So what are resources? To put it bluntly, in the computer that is a pile of data. It's just that this pile of data has many forms for our java program, generally there are File, URL, InputStream and so on. There are many kinds of files alone: ​​configuration files, java class files, jps files, pictures, css, js files and so on. In the face of all kinds of resources, when we design an interface for reading resources, we need to provide methods for different forms of resources, so that our interface is still bound with the actual resource form, and it is not completely abstract. . In addition, the storage location of resources in java programs is also different. Some are stored in the classpath, some are stored in the file system, and some are stored in the web application. For resources in different locations, Java programs have different methods to obtain these resources. 
A. Get the resources in the classpath: 
Java code 
URL url = this.getClass().getResource("resource_name");  
URL url = this.getClass().getClassLoader().getResource("resource_name");  
URL url = Thread .currentThread().getContextClassLoader().getResource("resource_name");  

So why are there three ways to obtain resources under the classpath in jdk? There is some origin to this. 
The first line of code is obtained by using an instance of the Class class, and the second line of code is obtained by using the classloader that loads the current class. Looking at the source code in the jdk, you will find that the instance of the class class finally delegates the loading of its classloader to obtain resources. 
Java code 
public java.net.URL getResource(String name) {  
    name = resolveName(name);  
    ClassLoader cl = getClassLoader0();  
    if (cl==null) {  
        // A system class.  
        return ClassLoader. getSystemResource(name);  
    }  
    return cl.getResource(name);  
}  

As can be seen from the above code, the loading of resources does not have the parent delegation mechanism used by class loading. Instead, if the classloader of the current class is not null, the resources are loaded from the classloader of the current class first. And only when the classloader of the current class is null will resources be loaded from the system classloader. This allows us to customize the configuration class to override some default configurations. Of course, if the classloader is not specially customized in the j2se application, the classes we write are loaded by the system classloader. What is the difference between using class to obtain resources and using classloader to obtain resources? The difference is in the resolveName(name) method. The two methods represent resource names differently. Below is a simple package structure, / denotes the root of the classpath 

|-com.cn.test 
   |-Test.class 
   |-test2.txt  
|-test1.txt 
Java code 
// Get the resource URL under the same package as the current class  
url1 = this.getClass().getResource("test2.txt");  
// Get the resources under the com.cn.test package , need to add /  
URL url2 = this.getClass().getResource("/com/cn/test/test2.txt");  
// Get the resource URL under the classpath root  
url3 = this.getClass().getClassLoader() .getResource("test1.txt");  
// Get the resource URL under the package com.cn.test  
url4 = this.getClass().getResource("com/cn/test/test2.txt");  

and the third For the explanation of using the contextClassLoader of the current thread to obtain resources, please refer to my other article  B. Java code  for obtaining resources in the
file system  // 1. Obtaining the File object   File file = new File("test.txt");   // 2 , Get the byte stream of the File object   InputStream in = new FileInputStream(file);  






It is worth noting that the name parameter in the File constructor File(String name) can be a relative path or an absolute path. Relative paths are relative to System.getProperties("user.dir").
C. Obtain the resource 
Java code  in the web application
servletContext.getResourceAsStream(resource_name);  

resource_names is the path representation relative to the webroot. For example, to obtain web.xml, resource_name is represented as "/WEB-INF/web.xml". 

    Faced with the various resource representations and storage locations described above, isn't there a unified processing method in java? Yes, java.net.URL. 
From the name point of view URL (Uniform Resource Locator) Uniform Resource Locator. Looks good and powerful. But many times using it can't locate the resources we need. 
    First of all, the protocol that can be accessed by the standard URL in jdk is very limited (of course it can be extended, but it is very troublesome); commonly used are http, file, ftp and so on. It does not provide access to resources in the classpath and servletContext. 
    Also, it doesn't provide a way to tell if a resource exists. Every time an exception is thrown when we actually go to get the resource, we can know that the resource cannot be obtained. 
    Secondly, the responsibilities of the URL class are not clearly divided, and it is used to indicate that resources are useful to obtain their resources.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325472788&siteId=291194637