简体   繁体   English

使用FileInputStream从相对路径读取File

[英]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. 我也尝试将路径指定为“ Audio / w1.wav”,“ Audio // w1.wav”,但是它不起作用。

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. 这应该打印您所处的整个路径,以c:\\/开头,具体取决于您的操作系统。

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. 如果不是,请调整路径或移动文件。

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

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