各种输入输出流以及他们的使用举例,transient定义变量的区别

package com.gxnu.study.bean;

import java.io.Serializable;

public class Dog implements Serializable{
private String name;
private transient int age;
public Dog() {
super();
// TODO Auto-generated constructor stub
}
public Dog(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Dog [name=" + name + ", age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}

package com.gxnu.study.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.junit.Test;

import com.gxnu.study.bean.Dog;

public class FileInputStreamEx {
public static void main(String[] args) {
try(
FileInputStream fis = new FileInputStream("e:\\a.xml");
BufferedInputStream bis = new BufferedInputStream(fis)
){
byte[] arr = new byte[3];
int len = 0;
while((len = bis.read(arr))>0){
String str = new String(arr,0,len);
System.out.println(str);

}
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());

}

}

@Test
public void testOutputStream(){
try(
FileOutputStream fos = new FileOutputStream("e:/b.ser");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
){
Dog dog1 = new Dog("蓝",3);
Dog dog2 = new Dog("小米",4);
oos.writeObject(dog1);
oos.writeInt(88);
oos.writeObject(dog2);
oos.writeUTF("你是谁");

}catch(Exception e){
e.printStackTrace();
}
}

@Test
public void testReadObject(){
try(
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("e:\\b.ser")));
){
ois.readObject();
//ois.readInt();
ois.skipBytes(4);
Dog dog = (Dog) ois.readObject();
System.out.println(dog);
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());

}

}
@Test
public void testnioRead(){
try(
FileChannel fc = new FileInputStream("E:\\a.xml").getChannel();
){
ByteBuffer bb = ByteBuffer.allocate(3);
while(fc.read(bb)>0){

bb.flip();//1.limit指向position,2.position指向0
byte[] arr = new byte[3];
for(int i=0;i<bb.limit();i++){
arr[i]=bb.get();
}
System.out.println(new String(arr,0,bb.limit()));
bb.position(0);
}
}catch(Exception e){
e.printStackTrace();
}
}


}

猜你喜欢

转载自www.cnblogs.com/jiminluo/p/min.html