由于要做打印机中文打印,使用Java调用打印机串口打印。
打印机内部已经包含GBK中文字符集,在发送打印指令后发现不能正常打印,很是疑惑。
经确认原因如下:
Java文件使用UTF-8保存,打印字符为中文,调用OutputStream打印时String cmd转换为bytes[]时,使用如下方法:
cmd.toBytes("GBK");
现状
Java文件编码 | encoding | 结果 |
UTF-8 | UTF-8 | NG |
UTF-8 | GBK | Ok |
GBK | GBK | OK |
GBK | UTF-8 | NG |
结论:由于打印机只能使用GBK字符集,所以只要编码后能够使用GBK字符集转换就行了。
Java文件的保存格式没有关系。
以下是我的测试代码,如有问题可以交流。
package testsource;
import java.io.*;
/**
* @author zivey 2008/02/26 15:34:22
*
*/
public class FileWriter {
public static void main(String[] args) throws Exception {
FileWriter t = new FileWriter();
int i =0;
String sourceStrig = "中国china";
t.Write(sourceStrig,null,"c:/test"+i+0+".txt");
t.Write(sourceStrig,"GBK","c:/test"+i+1+".txt");
t.Write(sourceStrig,"UTF-8","c:/test"+i+2+".txt");
t.Write(sourceStrig,"US-ASCII","c:/test"+i+3+".txt");
t.Write(new String(sourceStrig.getBytes("GBK"),"UTF-8"),null,"c:/test"+i+4+".txt");
t.Write(new String(sourceStrig.getBytes("UTF-8"),"UTF-8"),null,"c:/test"+i+5+".txt");
t.Write(new String(sourceStrig.getBytes("GBK"),"GBK"),null,"c:/test"+i+6+".txt");
t.Write(new String(sourceStrig.getBytes("UTF-8"),"UTF-8"),null,"c:/test"+i+7+".txt");
t.Write(new String(sourceStrig.getBytes("ISO-8859-1"),"GBK"),null,"c:/test"+i+8+".txt");
t.Write(new String(sourceStrig.getBytes("ISO-8859-1"),"UTF-8"),null,"c:/test"+i+9+".txt");
}
void Write(String message, String fileType,String fileName) {
try {
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
OutputStream fileOut = new FileOutputStream(file, true);
Writer fileWriter;
if (fileType == null) {
fileWriter = new OutputStreamWriter(fileOut);
} else {
fileWriter = new OutputStreamWriter(fileOut, fileType);
}
fileWriter.write(message);
fileWriter.close();
fileOut.close();
} catch (Exception e) {
}
System.out.println("write file ok,file name:"+fileName);
}
}