java23_JAVA 23 字符编码问题

4849617.html

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 ts = new TreeSet();

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 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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值