java实现在不同编码之间进行文件转换,使用 InputStreamReader 或者FileReader 类,它们可以自动地把某个特定字符编码转换为本地字符代码。否则就使用DataOutputStream 类当中的writeUTF()方法以Unicode 文本写字符串,当然,读取的时候必须使用DataInputStream 打开它,并且使用readUTF()方法读取这些字符串。
为什么要转换编码呢?大家都知道,Java 语言是以Unicode 为基础的,但是操作系统都有它们自己内部的可能是与Unicode 不兼容的编码方式,所以用户收到的输入可能属于不同的代码系统,程序显示给用户的字符串最终必须使用当地的操作系统可以识别的方法对其进行译码。
转换不同编码,具体实现步骤:
1.编写ConvertEncoding 类的基本框架,该类包括main()方法、usage()方法和convert()方法:
1 | public class ConvertEncoding |
2 | { |
3 | public static void main(String[] args); |
4 | public static void usage(); |
5 | public static void convert(String infile, String outfile, String from, String to) |
6 | throws IOException, UnsupportedEncodingException; |
7 | } |
2.Main()方法实现了实现了把一种编码形式的文件,转换成为另外一种编码形式:
01 | public static void main(String[] args) |
02 | { |
03 | String from = null , to = null ; |
04 | String infile = null , outfile = null ; |
05 | for ( int i = 0 ; i <args.length; i++) { // 处理命令行参数 |
06 | if (i == args.length- 1 ) usage(); . |
07 | if (args[i].equals( "-from" )) from = args[++i]; |
08 | else if (args[i].equals( "-to" )) to = args[++i]; |
09 | else if (args[i].equals( "-in" )) infile = args[++i]; |
10 | else if (args[i].equals( "-out" )) outfile = args[++i]; |
11 | else usage(); |
12 | } |
13 | try { convert(infile, outfile, from, to); } // 开始转换 |
14 | catch (Exception e) |
15 | { // 处理例外 |
16 | System.exit( 1 ); |
17 | } |
18 | } |
3.usage()方法实现了提醒用户命令行的正确输入,代码如下:
1 | public static void usage() |
2 | { |
3 | System.err.PRintln( "Usage: java ConvertEncoding <options>/n" + |
4 | "Options:/n/t-from <encoding>/n/t" + |
5 | "-to <encoding>/n/t" + |
6 | "-in <file>/n/t-out <file>" ); |
7 | System.exit( 1 ); |
8 | } |
4.Convert()方法实现了编码方式的转换,代码如下:
01 | public static void convert(String infile, String outfile, String from, String to) |
02 | throws IOException, UnsupportedEncodingException |
03 | { |
04 | // Set up byte streams. |
05 | InputStream in; |
06 | if (infile != null ) in = new FileInputStream(infile); |
07 | else in = System.in; |
08 | OutputStream out; |
09 | if (outfile != null ) out = new FileOutputStream(outfile); |
10 | else out = System.out; |
11 | // 设置缺省的编码方式 |
12 | if (from == null ) from = System.getProperty( "file.encoding" ); |
13 | if (to == null ) to = System.getProperty( "file.encoding" ); |
14 | // 建立用于读写的字符流 |
15 | Reader r = new BufferedReader( new InputStreamReader(in, from)); |
16 | Writer w = new BufferedWriter( new OutputStreamWriter(out, to)); |
17 | /** 把字符从输入Copy 到输出。InputStreamReader |
18 | * 把字符从原始编码方式转为Unicode |
19 | * OutputStreamWriter 则把字符从Unicode 编码转换为指定的输出编码方式 |
20 | * 不能用指定输出编码方式编码的字符输出为'?' |
21 | **/ |
22 | char [] buffer = new char [ 4096 ]; |
23 | int len; |
24 | while ((len = r.read(buffer)) != - 1 ) . |
25 | w.write(buffer, 0 , len); . |
26 | r.close(); . |
27 | w.close(); |
28 | } |
注意:ConvertEncoding 类需要引入import java.io.*;
天骄国际美易购随心所欲新闻热点
疑难解答