1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
/**
* JConv to convert a file to another encoding.
*
* @author Natha
*/
public class JConv {
/** HELP_USE */
private static String HELP_USE = "jconv.jar [-h] [-f encoding] [-t encoding] [inputfile]";
/**
* @param args
*/
public static void main(String[] args) {
if (args.length == 0) {
System.out.println(HELP_USE);
System.exit(0);
}
boolean error = false;
String encodf = null;
String encodt = null;
File input = null;
for (int i = 0; i < args.length; i++) {
try {
if (args[i].trim().equals("-h")) {
System.out.println(HELP_USE);
System.exit(0);
} else if (args[i].trim().equals("-f")) {
i++;
encodf = args[i];
} else if (args[i].trim().equals("-t")) {
i++;
encodt = args[i];
} else if (args[i].trim().startsWith("-")) {
error = true;
} else {
input = new File(args[i]);
if (!input.exists() || !input.isFile()) {
error = true;
}
}
} catch (Throwable t) {
error = true;
}
}
if (error || encodf == null || encodt == null || input == null) {
System.out.println(HELP_USE);
System.exit(0);
} else {
System.out.println("Input file: " + input.getAbsolutePath());
System.out.println("Encode from: " + encodf);
System.out.println("Encode to: " + encodt);
}
// controls
if (!input.canRead() && !input.canWrite()) {
System.out.println("Rights error: The file cannot be readed or riten.");
System.exit(0);
}
// -- change encoding
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
File tmpFile = File.createTempFile("jconv", "tmp", new File(System.getProperty("java.io.tmpdir")));
isr = new InputStreamReader(new FileInputStream(input), encodf);
osw = new OutputStreamWriter(new FileOutputStream(tmpFile), encodt);
int n = 0;
char[] cbuf = new char[1024];
while ((n = isr.read(cbuf)) != -1) {
System.out.print(".");
osw.write(cbuf, 0, n);
}
isr.close();
osw.close();
System.out.println("end");
if (input.delete()) {
tmpFile.renameTo(input);
System.out.println("Change encoding OK");
} else {
System.out.println("Cannot delete original file.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
isr.close();
} catch (IOException e) {}
try {
osw.close();
} catch (IOException e) {}
}
}
} |
Partager