Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why does my Program Overwrite existing Files?

 
Kevin Simonson
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm taking a look at the page labeled "Moving a File or Directory" at web page "docs.oracle.com/javase/tutorial/essential/io/move.html", in an attempt to learn some of the new features of Java 1.7. This page describes the {Files.move()} method and says that it "takes a varargs argument" and describes as one possible argument "REPLACE_EXISTING--Performs the move even when the target file already exists." Doesn't that mean that if this argument is not specified and the target file already exists, that the move should not occur?

That was my impression, so I wrote the code:

This code is designed to either move a file from one location to another (if the last argument is not a directory), or to move one or more files to a directory (if the last argument is a directory). Note that at no time do I specify argument "REPLACE_EXISTING"; on the other hand I do specify argument "ATOMIC_MOVE", because if there's some problem along the way I don't want pieces of my files existing anywhere.

This program works just fine as long as moving the files would not overwrite any other files. But when I create two small files, call them "Uvw.java" and "Xyz.java", and create directory "Zqj", and copy "Uvw.java" into "Zqj", and execute "java Move Uvw.java Xyz.java Zqj", the copy of "Uvw.java" in "Zqj" gets overwritten! Can anyone tell me why this is happening? Shouldn't {AccessDeniedException} get thrown when I try to move "Uvw.java" to the "Zqj" directory?

Kevin S
 
Prasad Saya
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is some info after reading your question and observations (please note that I did not study or try your code).

I had used the move() method and made some notes sometime back. Based on my notes here are two points:
1. When the ATOMIC_MOVE copy option is used, the move replaces any existing non-directory target file.
2. AccessDeniedException is thrown if the target file is an existing directory, when ATOMIC_MOVE option is specified.

The notes can be accessed at blog post titled: Notes on Java File IO (NIO 2) API's Files.move()

I hope this is useful.

Prasad.
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that the javadoc for ATOMIC_MOVE says
If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException.

It sounds like the JRE implementation you are using chose to overwrite the file
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic