0

I have a text file that looks like this fileName | path. I read the text file and split it at the |. Now I want to use the filename and the path to copy files from one directory to another.

Here is what I have so far, the result I get is as follows:

file to be copied: test.jar to path: c:/test
c:\InstallFiles\test.jar
c:\test
c:\test

here is my code:

    String record = "";
    FileReader fileReader = null;
    String curDir = System.getProperty("user.dir");
    File file = new File(curDir + "/InstallFiles.txt");
    File installFiles = new File("c:/InstallFiles");
    File[] files = installFiles.listFiles();
    try {
        fileReader = new FileReader(file);
        BufferedReader myInput = new BufferedReader(fileReader);
        while ((record = myInput.readLine()) != null) {
            String[] recordColumns = record.split("\\|");

            String fileName = recordColumns[0].toString().trim();
            String path = recordColumns[1].toString().trim();

            System.out.println("file to be copied: " + fileName + " to path: " + path);
            Path source = Paths.get(installFiles +"/"+ fileName);
            System.out.println(source);
            Path target = Paths.get(path);
            System.out.println(target);
            Files.copy(source, target);
            System.out.println("Copied file: " + fileName + " to " + path);
        }
        myInput.close();
        fileReader.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
4

1 に答える 1

0

ほとんどの場合、何らかの形でIOExceptionスローされます。あなたが提供している情報からは理由がわかりません。

catchブロック内のコードを次のように変更することをお勧めします。

} catch (Exception e) {
    e.printStackTrace();
}

これにより、エラーが発生した理由に関するより良い情報が得られる可能性があります。


編集:

問題が発生する理由の1つの考えられる推測は、宛先ファイル(c:\test)がすでに存在していることです。このjavadocのドキュメントによると、まだ行っていないオプションFileAlreadyExistsExceptionを指定しない限り、を取得することになりますREPLACE_EXISTING

于 2013-01-22T12:22:14.910 に答える