0

I want to read some data for my app. Here my code:

 URL url = Myclass.class.getResource("/data/file.txt"); //Myclass is my class name
    File file = new File(url.toString());  //maybe I met error here. 
//File Constructor just receive String object, I don't know how to convert
    FileInputStream reader = new FileIputStream(file);

I don't know how to change url to File to read it. Please tell me how to solve.

Thanks :)

1

1 Answer 1

1

You can't read a resource as if it were a file. The following syntax should work:

InputStream resource = MyClass.class.getResourceAsStream("/data/file.txt");

To avoid relative / absolute path issues, you can also use:

InputStream resource = MyClass.class.getClassLoader().getResourceAsStream("/data/file.txt");
Sign up to request clarification or add additional context in comments.

8 Comments

I meet error: FileNotFound Exception, although I'm sure that file.txt in data folder
How about getResourceAsStream("data/file.txt");? (without the leading /)
Yes. I still meet this error. I can use getresource when I load an image:Toolkit.getDefaultToolkit().getImage(View.class.getResource("/data/icon.png"));
See my edit. You can also have a look at stackoverflow.com/questions/873960/…
"although I'm sure that file.txt in data folder" Test it by looking inside the Jar. (Sheesh..)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.