开发者

Saving a file using JFileChooser

I want to save a file to another directory which user selects from one directory. I know that JFileChooser can be use to select a file. But instead of using any output streams kind of things is there a开发者_如何学Cny way to move a file from one location to another in Java?


Only and only if they are on the same local disk file system, you can use File#renameTo() for this.

File sourceFile = createItSomehow();
File targetFile = chooser.getSelectedFile();

boolean renamed = sourceFile.renameTo(targetFile);

if (!renamed) {
    // Well, perhaps they are not on the same disk?
}

For all other cases, you're really better off by just streaming it. See also the linked javadoc:

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜