在做国际化的时候,要不停的对表现层的标签和用户提示信息进行转码。大家一般都会使用JDK自动native2Ascii进行处理。为了简化开发人员对windows DOS下的操作,整理一个开发人员熟悉的JAVA文件进行处理。共享一下代码:
I18NClass 是文件处理类:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class I18NClass {
/**操作系统的字符级*/
private static String forwardEncoding = "UTF-8";//
private static String reverseEncoding = "UTF-8";
/**
* 正向转化文件为ASCII字节码文件
*
* @param src
* @param dest
*/
public void forward(String srcFile, String destFile) {
Runtime rn = Runtime.getRuntime();
FileOutputStream fos = null;
String srcPath = FilePathSymbol(srcFile);
String destPath = FilePathSymbol(destFile);
if (srcPath.length() > 0 && destPath.length() > 0) {
try {
String command = "native2ascii -encoding " + forwardEncoding +" "
+ srcPath;
Process process = rn.exec(command);
InputStream is = process.getInputStream();
byte[] buf = new byte[1024];
int bytesRead;
//目标文件是否存在
if(destPath.length()>0){
int post = destPath.lastIndexOf(File.separator);
String path = destPath.substring(0, post);
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
}
fos = new FileOutputStream(new File(destFile));
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} else {
System.out.println("核实文件是否都写有路径!");
}
}
/**
* 反向转化文件为源码文件
*
* @param dest
* @param src
*/
public void reverse(String srcFile, String destFile) {
Runtime rn = Runtime.getRuntime();
String srcPath = FilePathSymbol(srcFile);
String destPath = FilePathSymbol(destFile);
FileOutputStream fos = null;
if (srcPath.length() > 0 && destPath.length() > 0) {
try {
String command = " native2ascii -reverse -encoding "
+ reverseEncoding +" "+ srcPath;
System.out.println(command);
Process process = rn.exec(command);
InputStream is = process.getInputStream();
byte[] buf = new byte[1024];
int bytesRead;
fos = new FileOutputStream(new File(destFile));
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.flush();
fos.close();
} catch (IOException e) {
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} else {
System.out.println("核实文件是否都写有路径!");
}
}
/**
* 判断文件是否存在
*
* @param filePath
* @return
*/
private String FilePathSymbol(String filePath) {
if (null != filePath && !"".equals(filePath)) {
if (filePath.indexOf("/") != -1) {
return filePath.replace("/", File.separator);
}
} else {
System.out.println("【" + filePath + "】不存在源文件!");
}
return "";
}
public static String getForwardEncoding() {
return forwardEncoding;
}
public static void setForwardEncoding(String forwardEncoding) {
I18NClass.forwardEncoding = forwardEncoding;
}
public static String getReverseEncoding() {
return reverseEncoding;
}
public static void setReverseEncoding(String reverseEncoding) {
I18NClass.reverseEncoding = reverseEncoding;
}
}