This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Copying files Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Copying files" Watch "Copying files" New topic
Author

Copying files

Jacob Steingart
Ranch Hand

Joined: Mar 28, 2008
Posts: 63
Hey, I'm working on a program that involves having a music library. I want to have the songs be imported into a file that will be accessible by the program (in a folder inside the folder containing the program's class file), but I don't want to just move the files. How would I do this? I would be moving audio files.


I never know what to put in my signature...
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24193
    
  34

Hi Jacob,

Copying a file in Java is very simple. You just

1) Open the old file for reading,
2) Open the new file for writing
3) Read each byte from the old file and
4) Write it into the new file
5) Close both the files.

You can either do this with a FileInputStream/FileOutputStream pair, or if you want to get fancy, you can use FileChannels. Either way, it's basically the same.

Since it's binary data, be sure to read and write bytes, not chars.


[Jess in Action][AskingGoodQuestions]
 
jQuery in Action, 3rd edition
 
subject: Copying files
 
It's not a secret anymore!