开发者

File input in Java

开发者 https://www.devze.com 2023-02-13 20:05 出处:网络
I simply want to add some text on my JTextPane and I\'m having the following problem: I am using the file class to load an external textfile:

I simply want to add some text on my JTextPane and I'm having the following problem:

I am using the file class to load an external textfile:

File file = new File("/my/program/pics/mytext.txt");

but the problem is that I always get FileNotFound exception! After a bit of research though I realised that only absolute filepaths work like for instance "c:\myfiles\mytext.txt"

What's 开发者_开发知识库wrong and how can I make it load a file stored in my package? (that is relative position)

Thanks


To get a classpath resource as InputStream, use Class#getResourceAsStream().

InputStream input = getClass().getResourceAsStream("/my/program/pics/mytext.txt");


If you want to load resources from your class path (in other words, from within your package structure) you would have to use a different strategy.

(Sure, it's still a file on your file system, but when your application is distributed it most likely will not be)

Resources from the class path can be loaded using a class loader, like so:

InputStream stream = getClass().getResourceAsStream("/path/to/your/file/")

This path begins at the root of your class path/package structure.


You should make it work with a relative path. You must consider the "starting folder" as the folder in which the program will execute. For instance, if you are running it from Eclipse, the starting folder is the root folder of your project (the one containing the .project file).

For example, if your file is located in the folder pics in the root folder, use this code :

File file = new File("pics/mytext.txt"); 
0

精彩评论

暂无评论...
验证码 换一张
取 消