您的位置:首页 > 编程语言 > Java开发

Java学习第21天:IO流之知识补充

2014-02-16 13:16 351 查看
 -------
android培训、java培训、期待与您交流! ---------- 

until21

IO流

1.对象的序列化

2.管道刘

3.RandomAccessFile

4.操作基本数据类型的流对象DataStream

5.ByteArrayStream

6.转换流的字符编码

7.字符编码

8.练习

 

对象的序列化

对象的持久化(对象存在硬盘中!又成为序列化)

一般成对使用:ObjectInputStream ==>readObject

ObjectOutputStream ==>writeObject

静态是不许允许序列化的!只能序列化堆内存数据!

关键字:transient 使成员无法被序列化!

NotSerializableException - 某个要序列化的对象不能实现 java.io.Serializable 接口:该接口是没有方法的!称为标记接口

标记的方法是根据类中的成员标记了UID!~可以通过

public static fianl long serialVersionUID = 444;设定

public class ObjectOutIn {

public static void main(String[] args)throws IOException, ClassNotFoundException {
// 序列化的操作练习
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("ObjectInOut.txt"));
oos.writeObject(new Person("zhangwan",10));
oos.close();
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("ObjectInOut.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
}

}
class Person implements Serializable
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString()
{
return name+"="+age;
}
}


管道流

(io和多线程的结合!)

PipedInputStream和PipedOutputStream

输入输出可以直接进行链接!通过结合线程使用!

public class Piped {

public static void main(String[] args) throws IOException {
// Piped
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pis.connect(pos);
Read r = new Read(pis);
Write w = new Write(pos);
new Thread(r).start();
new Thread(w).start();

}

}
class Read implements Runnable
{
private PipedInputStream in;
Read(PipedInputStream in)
{
this.in = in;
}
public void run()
{
try {
byte[] buf = new byte[1024];
System.out.println("数据读取前");
int len = in.read(buf);
System.out.println("数据读取后");
String s = new String(buf,0,len);
System.out.println(s);
in.close();
} catch (Exception e) {
throw new RuntimeException("读取失败");
}
}
}
class Write implements Runnable{
private PipedOutputStream out;
Write(PipedOutputStream out)
{
this.out = out;
}
public void run(){
try {
Thread.sleep(4000);
System.out.println("数据写入前");
out.write("hahahah".getBytes());
out.close();
} catch (Exception e) {
throw new RuntimeException("写入失败");
}
}
}


RandomAccessFile

随机访问文件!自身具备读写能力!

通过SkipBytes(int x),seek(int x)来达到随机访问

 






 

 

public class RandomFile {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ReadFile();
}
public static void ReadFile() throws IOException
{
RandomAccessFile raf = new RandomAccessFile("randomaccessfile.txt","r");
//调整对象指针
raf.seek(8);
//跳到指定指针
raf.skipBytes(4);
byte[] buf = new byte[4];
raf.read(buf);
String s = new String(buf);
int i = raf.readInt();
System.out.println(i);
System.out.println(s);
}
public static void Demo()throws IOException
{
RandomAccessFile raf = new RandomAccessFile("randomaccessfile.txt","rw");
raf.write("王五".getBytes());
raf.writeInt(32);
raf.write("初中".getBytes());
raf.writeInt(60);
raf.close();
}

}


 

操作基本数据类型的流对象DataStream

DataInputStream DataOutputStream
public class OtherClass {

public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
Demo();
Demo_1();
}
public static void Demo() throws IOException
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeInt(2);//int 四个字节
dos.writeBoolean(true);//一个字节
dos.writeDouble(1.1);//double八个字节
dos.writeUTF("你好");
dos.close();
}
public static void Demo_1()	throws IOException
{
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
int i = dis.readInt();
boolean b = dis.readBoolean();
double d = dis.readDouble();
String s = dis.readUTF();
System.out.println(i+d+s);
System.out.println(b);
}

}


 

ByteArrayStream

用于操作字节数组的流

ByteArrayInputStream和ByteArrayOutputStream

 


用于操作字符数组的流

CharArrayReader 和 CharArrayWriter

用于操作字符串的流

StringReader 和 StringWriter

因为不调用底层数据!所以可以不用关闭流!

public static void Demo_2()
{
ByteArrayInputStream bais = new ByteArrayInputStream("ADCF".getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lin = 0;
while((lin=bais.read())!=-1)
{
baos.write(lin);
}
System.out.println(baos.toString());
}


 

 

转换流的字符编码

转化流:InputStreamReader  OutputStreamWriter

常见的标准编码表:

ASC II

美国标准信息交换吗!一个字节的7位可以表示

ISO8859-1

拉丁码表!欧洲表!一个字节8位表示

GB2312

中国中文编码表!2字节!2高位都是1

GBK

上面的升级版

Unicode

国际标准码!所有文字用2个字节表示!JAVA用

UTF-8

最多用三个字节表示一个字符

 编码:字符串变成字节数组。

     解码:字节数组变成字符串。

      String-->byte[];  str.getBytes(charsetName);

      byte[] -->String: new String(byte[],charsetName);

在服务器端遇到乱码怎么解决:

    用服务器端的解码的码表编码一次,再按照数据原来编码的的码表解码。

    注意:该方法在GBK码表和UTF—8码表之间会出现问题,因为这两个码表都识别中文。

字符编码

 




 

练习



package until_21;
import java.io.*;
import java.util.*;
public class Practice_1 {

public static void main(String[] args) throws IOException {
Comparator cmp = Collections.reverseOrder();//自定义了一个比较器!
Set<Student> set = StudentInfoTool.getStudents();
StudentInfoTool.writeFile(set);
}

}
class Student implements Comparable<Student>//自定义了学生类!覆写了hashCode,equals,compareTo,toString方法
{
private String name;
private int yuwen,shuxue,yingyu,sum;
Student(String name,int yuwen,int shuxue,int yingyu)
{
this.setName(name);
this.setYuwen(yuwen);
this.setShuxue(shuxue);
this.setYingyu(yingyu);
setSum(yuwen+shuxue+yingyu);
}
public int getYuwen() {
return yuwen;
}
public void setYuwen(int yuwen) {
this.yuwen = yuwen;
}
public int getShuxue() {
return shuxue;
}
public void setShuxue(int shuxue) {
this.shuxue = shuxue;
}
public int getYingyu() {
return yingyu;
}
public void setYingyu(int yingyu) {
this.yingyu = yingyu;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int hashCode()
{
return name.hashCode()+sum*78;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("类型不同");
Student s = (Student)obj;
return this.name.equals(s.name);
}
public int compareTo(Student stu)
{
int num = new Integer(this.sum).compareTo(new Integer(stu.sum));
if(num==0)
return this.name.compareTo(stu.name);
return num;
}
public String toString()
{
return "Student["+name+","+yuwen+","+yingyu+","+shuxue+"]";
}
}
class StudentInfoTool{
//用于获取Student对象!从输入设备中获取!存入set集合中!可以自定义个比较器
public static Set<Student> getStudents() throws IOException
{
return getStudents(null);
}
//用于获取Student对象!从输入设备中获取!存入set集合中!可以自定义个比较器
public static Set<Student> getStudents(Comparator<Student> cmp) throws IOException
{
BufferedReader isr =
new BufferedReader(new InputStreamReader(System.in));
String line = null;
Set<Student> stus = null;
if(cmp==null)
stus=new TreeSet<Student>();
else
stus=new TreeSet<Student>(cmp);
while((line=isr.readLine())!=null)
{
if("over".equals(line))
break;
String[] s = line.split(",");
Student stu = new Student(s[0],
Integer.parseInt(s[1]),
Integer.parseInt(s[2]),
Integer.parseInt(s[3]));
stus.add(stu);
}
isr.close();
return stus;
}
//定义了一个输出的方法
public static void writeFile(Set<Student> s) throws IOException
{
BufferedWriter bw = new BufferedWriter(new FileWriter("practice_1.txt"));
for(Student stu : s)
{
bw.write(stu.toString()+"\t");
bw.write(stu.getSum()+"");
bw.newLine();
bw.flush();
}
bw.close();
}
}


 

-------
android培训、java培训、期待与您交流! ----------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息