JAVA 23 字符编码问题

gbk 两个字节。
 
 
转换流。
使用转换流的时候可以指定码表。
InputStreamReader in = new InputStreamReader(new FileInputStream("abc.txt"),"utf-8");//以utf-8形式读取文本文件
OutStreamWrtier out = new OutStreamWriter(new FileOutputStrem("abc.txt"),"utf-8")'//以utf-8编码写入文件。
 
编码:
字符串变字节数组
 
解码:
字节数组变字符串
 
String-->byte[]:str.getBytes(charserName)
byte-->String:new String(byte[],charsetName)
 
 
举例:
import java.io.*;
import java.util.*;
public class Test {
 
 public static void main(String[] args) throws IOException
 {
  String s="你好啊";
  byte [] b1 = s.getBytes("GBK");
  sop(Arrays.toString(b1));
 
  String s1 = new String(b1,"GBK");
  String s2 = new String(b1,"iso8859-1"); //换成utf-8就不行,因为utf-8和gbk都支持中文
 
  sop(s1);
  sop(s2);
 
  byte [] b2 = s2.getBytes("iso8859-1");
  String s3 = new String(b2,"gbk");
  sop(s3);
 }
 public static void sop(Object o)
 {
  System.out.println(o);  
 }
}
 
 
综合练习:
/*
有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhagnsan,30,40,60计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。
 
1,描述学生对象。
2,定义一个可操作学生对象的工具类。
 
思想:
1,通过获取键盘录入一行数据,并将该行中的信息取出封装成学生对象。
2,因为学生有很多,那么就需要存储,使用到集合。因为要对学生的总分排序。
 所以可以使用TreeSet。
3,将集合的信息写入到一个文件中。
 
 
*/
 
 
import java.io.*;
import java.util.*;
public class Test {
 
 public static void main(String[] args) throws IOException
 {
  InputStream in =System.in;
  BufferedReader bufr= new BufferedReader(new InputStreamReader(in));
  TreeSet<Student> ts = new TreeSet<Student>();
  while(true)
  {
   String line = bufr.readLine();
   if(line.equals("over"))
    break;
   else
   {
    String lines [] =line.split(" ");
    String a=lines[0];
    int b = Integer.parseInt(lines[1]);
    int c = Integer.parseInt(lines[2]);
    int d = Integer.parseInt(lines[3]);
    ts.add(new Student(a,b,c,d));
   }
  }
 
  BufferedWriter fw = new BufferedWriter(new FileWriter("d:\\STUDENT.TXT"));
  Iterator<Student> it = ts.iterator();
  while(it.hasNext())
  {
   Student st=it.next();
   
   fw.write(st.name);
   fw.write(" ");
   fw.write(Integer.toString(st.yuwen));
   fw.write(" ");
   fw.write(Integer.toString(st.shuxue));
   fw.write(" ");
   fw.write(Integer.toString(st.yingyu));
   fw.write(" ");
   fw.write(Integer.toString(st.total));
   fw.newLine();
 
  }
  fw.close();
 
 
 }
 public static void sop(Object o)
 {
  System.out.println(o);  
 }
}
 
class Student implements Comparable
{
 String name;
 int yuwen;
 int shuxue;
 int yingyu;
 int total;
 Student(String name,int yuwen,int shuxue,int yingyu)
 {
  this.name=name;
  this.yuwen=yuwen;
  this.shuxue=shuxue;
  this.yingyu=yingyu;
  total=yuwen+shuxue+yingyu;
 }
 
 public int compareTo(Object stu)
 {
  Student st = (Student)stu;
  return this.total-st.total;
 }
}
posted @ 2015-09-30 16:48  hitz&x  阅读(209)  评论(0编辑  收藏  举报