简体   繁体   English

使用File(URI uri)构造函数创建文件对象

[英]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. 在我的应用程序中,我需要创建目录的表示形式,该目录是包含<class_name>的包。 In short, I need to create a File object which represents that directory. 简而言之,我需要创建一个代表该目录的File对象。

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: 现在,问题是在创建File对象时,将引发此异常:

java.lang.IllegalArgumentException: URI is not hierarchical. java.lang.IllegalArgumentException:URI不是分层的。

May anyone shed light and help me solve this? 有人可以照亮并帮助我解决这个问题吗?

I don't use NetBeans. 我不使用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. 但是,如果可以在命令行中使用Java,请尝试使用此测试代码。

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());
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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