问题:java 实现不同编码方式的字符串的转换 ,在程序中实现异常处理、重复不终止输入,缓冲区bufferedreader的使用。
比如 “utf-8”,”utf-16”,”gbk”,”gb2312”,”iso-8859-1”,”ascii”的互相转换
部分代码
public static void main(String[] args) throws IOException, WrongStringException, WrongChoiceException {
BufferedReader in=null; //缓冲区
String sTemp=""; //暂存转换的结果
int temp=-1; //存储退出的方式 0、1(重来)、-1
trans s=new trans(); //main中(static)必须要对类实例化
while(true){ //程序循环输入要转换的代码
if(temp==0) break; //实现反复输入,唯有temp==0才会从主循环退出
System.out.println("Plese input the string you want to transform");
try{
in=null;
in =new BufferedReader(new InputStreamReader(System.in));
s.setAString(in.readLine()); //输入流
//唯有temp==0才会从主循环退出
}
catch(IOException e){
System.out.println(e);}
while(true){//输入选择哪种方法编码
if(temp==0||temp==1) break;
System.out.println("Please input the [choice 1] numbers which 0-6 represent respectively default utf-8 utf-16 gbk gb2312 iso-8859-1 ascii");
try{
in=null;
in =new BufferedReader(new InputStreamReader(System.in));
s.setEncodingSign(Integer.parseInt(in.readLine())); //输入流
s.stringEncoding();
//只有temp==0或者temp==1才会从循环退出
while(true){//输入选择哪种方法解码
if(temp==0||temp==1) break; //只有temp==0或者temp==1才会从循环退出
System.out.println("Please input the [choice 2] numbers which 0-6 represent respectively default utf-8 utf-16 gbk gb2312 iso-8859-1 ascii");
try {
in=null;
in =new BufferedReader(new InputStreamReader(System.in));
s.setDecodingSign(Integer.parseInt(in.readLine())); //输入流
}
catch(IOException e){
System.out.println("choice number is error!");}
//输出转换的结果
sTemp=s.stringDecoding(s.TranString);
System.out.println("The result of the translation is:"+sTemp);
while(true){//选择重来或退出
System.out.println("Please choose exit or again:");
try{
temp=s.ExitOrAgain();
if(temp==0||temp==1) break; //只有temp==0或者temp==1才会从循环退出
}
catch(IOException e){
System.out.println("exit error!");}
}
}
}
catch(IOException e){
System.out.println("choice number is error!");}
}
}
if(in!=null)
try {
in.close(); }//检查文件是否关闭
catch(IOException e){
System.out.println("文件关闭出错");}
else{ System.out.print("退出成功!");//提示信息
System.exit(0);
}
}
}