Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to copy files in Java code?

 
Nancy Zhang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm wondering whether there's some Java class/method to help copy files.

For example, my code wants to do this:
if specified file is a .java file, then ... certain processing...
else just copy this non-java file to a destination directory.

Thanks.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this out. Should work for files or directories.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm, reading all the responses to that article I'd be a bit shy about using it. Usually the answer is you're on your own to read the old file and write the new one. If you have to copy directories you need to detect the source directory and create the target directory. To copy bytes without corruption, use some streams for the job. Take a look at the JavaDoc, see if you can find classes that look appropriate. Give it a shot and let us see what you come up with!
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://jakarta.apache.org/commons/io/apidocs/org/apache/commons/io/IOUtils.html
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For that article I posted, if you are sure you will be moving files around on the same file system (not crossing partitions, ect...) the renameTo() function is fine. Otherwise I've heard the apache IOUtils mentioned above are very nice (although I haven't used them).
 
Nancy Zhang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great thanks for all responses. Will try the apache IOUtils.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic