如果不存在java,则复制到现有文件抛出错误

时间:2018-02-09 03:33:13

标签: java file-io error-handling

我正在尝试编写一个接收文件的方法,并将其复制到另一个文件中。如果目标文件不存在,则应该返回错误。我在这里得到了我的代码。

    public static void takeAndCopyFile(String sourceFile, String destinationFile) throws FileNotFoundException, IOException{
        FileInputStream fin = new FileInputStream(sourceFile);
        FileOutputStream fout = new FileOutputStream(destinationFile);

    try {
        File inFile = new File(sourceFile);
        File outFile = new File(destinationFile);

        byte[] buffer = new byte[1024];
        int length;
        if (outFile.exists()){

            while ((length = fin.read(buffer)) > 0 ) {
                fout.write(buffer,0,length);
            }
        }
    }catch (FileNotFoundException e){
        System.out.println("File not found!");
        e.printStackTrace();

    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        fout.close();
        fin.close();
    }

令我感到困惑的是,如果我传递一个不存在的文件名并且它应该继续FileNotFoundException,那么if语句显然是错误的。

感谢。

3 个答案:

答案 0 :(得分:0)

如果if条件不符合,则不会抛出异常,if语句的正文将不会被执行。

如果你想在这种情况下抛出异常,你必须明确地这样做,例如:

if(outFile.exists()){
     ...
}else{
   throw new FileNotFoundException();
}

答案 1 :(得分:0)

  

如果我传递一个不存在的文件名并且它应该继续FileNotFoundException,那么if语句是如何显然是假的

不,exists不会抛出FileNotFoundException异常,因为它的目的是测试是否存在。以后要避免这种例外。

测试此抽象路径名表示的文件或目录是否存在。

答案 2 :(得分:0)

简单的普通java 7 +

 Files.copy(Paths.get(filePath), Paths.get(filePath));

如果目的地不存在,则获得

  

线程中的异常" main" java.nio.file.NoSuchFileException: