简体   繁体   中英

Creating a File Object with File(URI uri) constructor

In my application, I need to create a representation of a directory which is the package where the <class_name> is contained. In short, I need to create a File object which represents that directory.

The code is as follows :

Package package1 = <class_name>.class.getPackage();
String string = "/" + package1.getName().replace('.', '/');
URL url = <class_name>.class.getResource( string );
File file = new File( url.toURI() );

Now, the problem is when creating the File object, this exception is thrown:

java.lang.IllegalArgumentException: URI is not hierarchical.

May anyone shed light and help me solve this?

I don't use NetBeans. So, I can't help you with that. But, if you can use java at the command line, then try using this test code.

package rick;
import java.net.*;
import java.io.*;
public class Test{
  public static void main(String[] args){
     Test test = new Test();
     Package package1 = test.getClass().getPackage();
     String string = "/" + package1.getName().replace('.','/');
     URL url = test.getClass().getResource(string);
     File  file = new File(url.toString());
     System.out.println(file.getPath());
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM