📄 convertencoding.java
字号:
import java.io.*;
public class ConvertEncoding {
public static void main(String[] args) {
String from = null, to = null;
String infile = null, outfile = null;
for(int i = 0; i <args.length; i++) { // 处理命令行参数.
if (i == args.length-1) usage(); .
if (args[i].equals("-from")) from = args[++i];
else if (args[i].equals("-to")) to = args[++i];
else if (args[i].equals("-in")) infile = args[++i];
else if (args[i].equals("-out")) outfile = args[++i];
else usage();
}
try { convert(infile, outfile, from, to); } // 开始转换.
catch (Exception e) { // 处理例外.
System.exit(1);
}
}
public static void usage() {
System.err.println("Usage: java ConvertEncoding <options>\n" +
"Options:\n\t-from <encoding>\n\t" +
"-to <encoding>\n\t" +
"-in <file>\n\t-out <file>");
System.exit(1);
}
public static void convert(String infile, String outfile,
String from, String to)
throws IOException, UnsupportedEncodingException
{
// Set up byte streams.
InputStream in;
if (infile != null) in = new FileInputStream(infile);
else in = System.in;
OutputStream out;
if (outfile != null) out = new FileOutputStream(outfile);
else out = System.out;
// 设置缺省的编码方式.
if (from == null) from = System.getProperty("file.encoding");
if (to == null) to = System.getProperty("file.encoding");
// 建立用于读写的字符流.
Reader r = new BufferedReader(new InputStreamReader(in, from));
Writer w = new BufferedWriter(new OutputStreamWriter(out, to));
/** 把字符从输入Copy到输出. InputStreamReader
* 把字符从原始编码方式转为Unicode
* OutputStreamWriter 则把字符从Unicode编码转换为指定的输出编码方式.
* 不能用指定输出编码方式编码的字符输出为'?'
**/
char[] buffer = new char[4096];
int len;
while((len = r.read(buffer)) != -1) .
w.write(buffer, 0, len); .
r.close(); .
w.close(); .
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -