【问题标题】:Incorrect path to file文件路径不正确
【发布时间】:2014-10-06 15:23:13
【问题描述】:

我不知道为什么,但是 outStream = new FileOutputStream(file)inStream = new FileInputStream(new File(file1.getName())) 抛出异常。我不知道该怎么做。

下面是这段代码:

        File tempf = new File(cmds[1]); //cmds is a String with filename cmds[1] and  pathname cmds[2] where to move the file
        File tempw = new File(cmds[2]);
        if(!tempf.isAbsolute() || !tempw.isAbsolute()){//here i make paths absolute
            tempf = new File(tempf.getAbsolutePath());
            tempw = new File(tempw.getAbsolutePath());
        }
        String from = cmds[1];
        String where = cmds[2];
        File file1 = tempf;
        File file2 = new File (tempw.toString() + "/" + new File(cmds[1]).getName());
        InputStream inStream = null;
        OutputStream outStream = null;
        try {
            inStream = new FileInputStream(new File(file1.getName())); //throws an exception
            outStream = new FileOutputStream(file2); //throws an exception too
            byte[] buffer = new byte[16384];
            int length;
            while ((length = inStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }

            if (inStream != null)
                inStream.close();
            if (outStream != null)
                outStream.close();
            file1.delete();

        } catch (IOException e) {
            System.err.println("permission denied");
        }
    } else {
        System.err.println("incorrect syntax");
    }
    continue;
}

看起来一切正常,但事实并非如此。我得到了

java.io.FileNotFoundException: C:\Users\Maxim\IdeaProjects\Testing\OneDrive\1234.txt

但我认为这是错误的路径。真实路径是C:\Users\Maxim\OneDrive

更新!发现问题是getAbsolutePath()返回的是项目所在的路径,但不是我需要的路径。我需要C:\Users\Maxim\OneDrive 但它返回C:\Users\Maxim\IdeaProjects\Testing\OneDrive 但是! .../Testng 没有 OneDrive!

【问题讨论】:

  • 显示异常!!!
  • 异常(尤其是标准库异常)的好处在于,它们可以告诉您它们发生的原因。

标签: java exception input stream output


【解决方案1】:

如果文件访问出现问题,例如文件不存在,FileInputStream 和 FileOutputStream 的构造函数会抛出错误。要阻止它抛出 FileNotFoundException,请确保在实例化 FileInput/OutputStream 对象之前创建文件。

try{
    FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
    e.printStackTrace();
}

查看文档here

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 2015-07-06
    • 2015-08-30
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    相关资源
    最近更新 更多