Alexander DeLarge
Alexander DeLarge

Reputation: 31

Java File object's renameTo method deletes my file instead of renaming it. Vistax64

Trying to take one mp3 file and rename it using a string variable. For example, I have a classical music folder, C:/classical, and I want a song called vivaldi renamed to FourSeasons. I want to find the absolute path of the initial file, C:/classical/vivaldi.mp3, then provide a string, "FourSeasons.mp3", and have the file C:/classical/vivaldi.mp3 changed to C:/classical/FourSeasons.mp3.

I've thought of using renameTo and file writer, but neither of these have given me desired results. RenameTo code : this returns false (rename failed), and tends to permanently delete my file.

public static void main(String[] args) {
File mp3 = new File("C:/mp3.mp3");
boolean renamestatus = mp3.renameTo(new File("song.mp3"));
System.out.println(renamestatus);
}

I've also tried to use FileReader and FileWriter to make an exact copy of the file, with a new name. This method outputs an mp3 file that skips and is nowhere near sounding like the input file This is my fileWriter code:

File inputFile = new File("C:/mp3.mp3");
File outputFile = new File("C:/song.mp3");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
  out.write(c);
in.close();
out.close();

Upvotes: 3

Views: 5572

Answers (5)

Prashant Vhasure
Prashant Vhasure

Reputation: 985

Its not deleting original, Its working fine, Just give complete path(Source file path + new name)

Upvotes: 0

Ninad Pingale
Ninad Pingale

Reputation: 7079

I also faced same problem,

I solved it using Absolute path of the new file object.

So in your case :

boolean renamestatus = mp3.renameTo(new File("song.mp3"));

should be

boolean renamestatus = mp3.renameTo(new File("C://song.mp3"));

Secondly, without using Absolute path, your file doesn't get deleted, but it is moved to your project's root folder with new name.

Upvotes: 5

CF711
CF711

Reputation: 341

When using renameTo you need to specify the path that you want the file to go to.For example with the one you are using the original path is "C:/mp3.mp3" you would want the path in renameTo to look like "C:/song.mp3". So your line would look something like this.

boolean renamestatus = mp3.renameTo(new File("C:/song.mp3"));

Hope that is helpful for you.

Upvotes: 2

Simeon
Simeon

Reputation: 7790

Try like this:

mp3.renameTo(new File("C:/song.mp3"));

You can also have a look at this and this answers.

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308249

FileReader and FileWriter are made to handle textual data only.

Your MP3 files are binary data and should be treated as such, so you'd need to use FileInputStream and FileOutputStream for reading/writing.

Upvotes: 1

Related Questions