Java – convert resource / stream to file

How can I do this?

File myFile = getFile(this.getClass.getResourceAsStream("test.txt"))

or

File myFile = getFile(this.getClass.getResource("test.txt"))

What code will I write in the GetFile () method?

Solution

Yo, you can do this

File f = new File(this.getClass().getResource("test.txt").toURI());
    System.out.println(f);

Output (my eclipse test)

D:\workspace1\x\target\classes\text.txt

But it will never work What if your resources are in a jar? You'll get

java.lang.IllegalArgumentException: URI is not hierarchical
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>