Files.copy is not working as expected. The copied file is always 0 bytes. Below is the code snippet
File sourceFile = new File(sorceFileName);
File destinationFile = new File(destinationFileName);
Files.copy(sourceFile.toPath(), destinationFile.toPath());
What is the reason for this? Running on Solaris OS.
If the target file already exists, you'll need to specify that you want it replaced
Files.copy(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
You haven't posted any stack trace, but if you don't add the above CopyOption
and the target file does exist, you will get a FileAlreadyExistsException
, as described in the comments by @fge and in the javadoc .
I believe you will need to add one more attribute REPLACE_EXISTING
Like this: Files.copy(source, target, REPLACE_EXISTING);
which in your case should be: Files.copy(sourceFile.toPath(), destinationFile.toPath(), REPLACE_EXISTING);
Have a read of http://docs.oracle.com/javase/tutorial/essential/io/copy.html I hope it will help. If you want to know other ways to copy files you may want to read this and this .
Unless there is a huge bug in Solaris' filesystem, which I seriously doubt, your scenario is only possible if the source file is actually empty.
Since you say it isn't, then the API must have thrown an exception and you don't tell. Possible exceptions are:
FileAlreadyExistsException
: target file already exists; use solution provided in other posts; AccessDeniedException
: meh, can't read source/write destination (many possible causes); NoSuchFileException
: path in destination file contains one path element which does not exist; FileSystemLoopException
: somewhere in the destination path is a symlink which loops on itself. And of course the classical IOException
and critical IOError
...
Also, since you generate Path
s from File
objects, you can have InvalidPathException
; unlike File
, you cannot create Path
objects from strings containing character sequences unmappable in your current encoding (not with the provided default FileSystem
implementations at least).
You HAVE to have an exception somewhere...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.