java io操作3

Dog.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.gxnu.bigdata.study.core.io.bean;

import java.io.Serializable;

public class implements Serializable {
private String name;
private transient int age;

public () {
super();
}

public (String name, int age) {
super();
this.name = name;
this.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;
}


public String toString() {
return "Dog [name=" + name + ", age=" + age + "]";
}

}

InputStreamEx.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.gxnu.bigdata.study.core.io.test;

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 org.junit.Test;

import com.gxnu.bigdata.study.core.io.bean.Dog;


public class InputStreamEx {
@Test
public void testInputStream(){

try(
FileInputStream fis = new FileInputStream("d:\aaa.xml");
BufferedInputStream bis = new BufferedInputStream(fis);
) {
byte[] arr = new byte[3];
int len = 0;
while((len=bis.read(arr))>0){
String s = new String(arr,0,len);
System.out.print(s);
}

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

}

@Test
public void testOutputStream(){
try (
FileOutputStream fos = new FileOutputStream("d:/dog.ser");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
){
Dog dog = new Dog("小黄",3);
oos.writeObject(dog);

//oos.writeUTF("我是xxx");

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

@Test
public void testTransient(){
try(
FileInputStream fis = new FileInputStream("d:/dog.ser");
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
) {
//ois.readObject();
//ois.skipBytes(4);
Dog dd = (Dog) ois.readObject();
System.out.println(dd);//Dog [name=小黄, age=0]因为age用transient声明所以为0

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

limaodeng

scribble