【问题标题】:read File from relative path using FileInputStream使用 FileInputStream 从相对路径读取文件
【发布时间】:2019-05-16 03:13:14
【问题描述】:

我想从相对路径读取文件。 我试过下面的代码

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

错误:

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

我也尝试将路径指定为“Audio/w1.wav”、“Audio//w1.wav”,但它不起作用。

如何让系统找到文件?

【问题讨论】:

标签: java path relative-path fileinputstream


【解决方案1】:

问题似乎是一条错误的路径。要追踪它,首先要找出. 的位置。为此运行:

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

这应该打印您所在的整个路径,以 c:\ 或 / 开头,具体取决于您的操作系统。

现在在资源管理器中查看该文件夹,您希望该文件夹中 . 中的所有内容吗?

  • 如果是:检查拼写错误并在\ 和/ 之间切换并检查文件访问权限?
  • 如果不是:调整路径或移动文件。

【讨论】:

    【解决方案2】:

    你可以这样来获取文件,

    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());
    

    【讨论】:

    • 类加载器资源 = this.getClass().getClassLoader(); URL 路径 = resource.getResource("/Audio/w1.wav"); in=new FileInputStream(new File(path.getFile())); swar=新音频流(输入); AudioPlayer.player.start(swar);
    • 线程 "AWT-EventQueue-0" java.lang.NullPointerException 中的异常
    • 异常在 --> in=new FileInputStream(new File(path.getFile()));怎么办?
    • 首先尝试打印路径,看看你是否在正确的路径,尝试获取文件,看看是否可以,我不确定你的 in 变量是什么。
    • // 我不确定你的 in 变量是什么。 // --> 类加载器资源 = this.getClass().getClassLoader(); URL 路径 = resource.getResource("/Audio/w1.wav"); InputStream in=new FileInputStream(new File(path.getFile())); AudioStream swar=new AudioStream(in); AudioPlayer.player.start(swar);我想播放具有相对路径的音频文件。请帮忙
    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多