1 /*****************************************Java基本数据的写入和读取操作,分别是字节数据输入流java.io.DataInputStream和字节输出流java.io.DataOutoutStream,使用字节数据流进行基本的写入和读取操作时,可以不必担心平台之间数据大小差异的问题,因为java的数据类型占用的空间大小都是有规定的。******************************************/
/****************************************下面是一个使用字节数据输入输出流的实例,使用DataInputStream与DataOutputStream来读取People中的数据成员。*******************************************************/
//关于字节数据输入、输出流的小例子
public class People {
2 private String name;
3 private int age;
4 public int getAge(){
5 return age;
6 }
7 public String getName(){
8 return name;
9 }
10 public void getName(String name){
11 this.name = name;
12 }
13 public People(String name,int age) {
14 // TODO Auto-generated constructor stub
15 super();
16 this.name = name;
17 this.age = age;
18 }
19 }
1 package test;
2
3 import java.io.DataInputStream;
4 import java.io.DataOutputStream;
5 import java.io.FileInputStream;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8
9 public class DataIOStreamTest2 {
10 public static void main(String[] args) {
11 //创建,并初始化文件名字符串
12 //创建,并初始化People数组
13 People[] people = {
14 new People("关云长",21),
15 new People("云中燕",22)
16 };
17 try{
18 String filename = "C:\\Users\\lenovo\\Desktop\\2.txt";
19 DataOutputStream dataOutputStream = new DataOutputStream(
20 new FileOutputStream(filename)); //创建DataOutputStream对象
21 for(People Employee:people){ //使用for遍历
22 dataOutputStream.writeUTF(Employee.getName()); //写入字符串
23 dataOutputStream.writeInt(Employee.getAge()); //写入数据
24 }
25 dataOutputStream.flush(); //读出所有数据至目的地
26 dataOutputStream.close(); //关闭流
27 DataInputStream dataInputStream = new DataInputStream(
28 new FileInputStream(filename));
29 for (int i = 0; i < people.length; i++) {
30 String name = dataInputStream.readUTF(); //读出字符串
31 int score = dataInputStream.readInt(); //读出int数据
32 people[people.length-1-i] = new People(name,score);
33 }
34 dataInputStream.close(); //关闭流
35 //输出还原后的数据
36 for(People i:people){
37 System.out.printf("%s\t%d%n",i.getName(),i.getAge());//格式化输出
38 }
39 }catch(IOException e){ //捕获异常
40 e.printStackTrace(); //抛出异常
41 }
42 }
43 }
最近一直在看IO流,学的有点慢,希望在这能记录下自己的一点一滴的进步吧。
/*****据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字****//*****据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字据说要150字****/