I have this java code that renames a file (or directory). There is a problem on Linux when I use some special characters, it works on Windows with these special characters. The way I try it is like this:
In windows
-
I create a direcotory called “326½_6”
-
I build a jar-file, and call it (java -jar) directly in the windows cmd (or linux shell), first param is the directory above, second param is a path to a new directory.
This works
I then transfer the directory to a Linux server using SFTP (WinSCP). I repeat the steps above, but it doesn’t work. I get this output:
Moving /home/user/testarea/326�_6/ to /home/user/testarea/test5/
— could not perform rename ——-
Is there anyway to make this work on a Linux machine???
the code:
public static void main(String [] args) {
String source = args[0];
String dest = args[1];
System.out.println(" - Moving " + source + " to " + dest);
File sourceFile = new File(source);
File destinationFile = new File(dest);
if (!sourceFile.renameTo(destinationFile)) {
System.out.println("--- could not perform rename -------");
}
System.out.println("Finished moving");
}
thanks!
It looks like Java on Linux is expecting file and directory names to be encoded in UTF-8, but when WinSCP creates the directory it encodes the name in latin1 or something similar, and the new name is not valid in UTF-8. Apparently this was the default behavior for WinSCP, the newer versions use UTF-8 by default.
An easy solution to make Java use the same encoding that SFTP used when creating the directory. This is done by changing the locale when running the JVM:
The locale en_US.iso8859_1 has to exist for this to work, though. You might be able to install new locales from the package repositories of your distribution. If not, you can read about how to define a locale with a specific encoding (and about this file name problem in general) in my blog.