开发者

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 renames开发者_如何转开发tatus = 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();


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.


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.


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.


Try like this:

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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜