简体   繁体   中英

read File from relative path using FileInputStream

I want to read a file from a relative path. I've tried the following code

InputStream in = new FileInputStream(".//Audio//w1.wav");

Error:

java.io.FileNotFoundException: .\Audio\w1.wav (The system cannot find the path specified)

I also tried to specify the path as "Audio/w1.wav", "Audio//w1.wav" but it does not work.

How can I get the system to find the file?

You can so something like this to get the file,

ClassLoader resource = this.getClass().getClassLoader();
URL path = this.getClass().getResource("/Audio/w1.wav");

//Since you have the path you can get the file as you want
//To get the file,  
File file = new File(path.getFile());

The problem seems to be a wrong path. To track that down, start with figuring out where . is. To do so run:

System.out.println(new File(".").getAbsolutePath());

This should print the entire path you're in, beginning with c:\\ or / depending on your os.

Now take a look at that folder in the explorer, is everything you expect to be in . in that folder?

  • If yes: check for typos and switch between \\ and / and check file access permissions?
  • If no: adjust your path or move the files.

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