2016.3.17(Java I/O系统)

操作 Java I/O输入输出流的基本步骤

1 创建管道
2 读写操作
3 关闭管道

输入流:

public class InputStreamTest {
public static void main(String[] args) {
//File
//String filePath
try {
InputStream in = new FileInputStream("file/test.txt");

// int i = 0;
//
// while(true){
// if((i = in.read()) != -1){
// System.out.println(i);
// }else{
// break;
// }
// }

int i = 0;
byte[] by = new byte[1024];
while(true){
if((i = in.read(by)) != -1){

}else{
break;
}
}

String info = new String(by);

String [] a = info.split("@");

System.out.println(a[0] + " " + a[1].trim());

in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


输出流:

public static void main(String[] args) {
try {
OutputStream out = new FileOutputStream("file/test.txt", true);
String str = "zhangsan@123";

out.write(str.getBytes());

out.flush();//多一步刷新操作
out.close();
} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

 

对象流大致和字节流、字符流一致,不过一定要实现serializable

public class ObjectStreamDemo {

/**
* @param args
*/
public static void main(String[] args) {

//ObjectOutputStream

try {
ObjectOutputStream outObj = new ObjectOutputStream(new FileOutputStream("file/object.txt"));

Student stu1 = new Student("张三", 22, "男");
Student stu2 = new Student("李四", 24, "男");

Set<Student> stus = new HashSet<Student>();
stus.add(stu1);
stus.add(stu2);

outObj.writeObject(stus);

outObj.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//ObjectInputStream
try {
ObjectInputStream inObj = new ObjectInputStream(new FileInputStream("file/object.txt"));

Object obj = inObj.readObject();

Set<Student> stu = (Set<Student>)obj;

for(Student su : stu){
System.out.println(su.getName());
System.out.println(su.getAge());
System.out.println(su.getGender());
}

inObj.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

对象流


public class Student implements Serializable{

private String name;
private int age;
private String gender;


public Student() {
super();
}


public Student(String name, int age, String gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}


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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}

}

posted @ 2016-03-17 23:15  稳重的橙子  阅读(133)  评论(0)    收藏  举报