Java中IO流应用举例

来源:互联网 发布:淘宝网店上架 编辑:程序博客网 时间:2024/06/08 17:57


package cn.io.demo;



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


import org.junit.Test;


import cn.io.entity.Student;


public class FileIo {


//字节输出流  写文件
@Test
public void testIO1() throws Exception{
FileOutputStream fos = null;
try {
fos = new FileOutputStream("F:/words.txt"); //强烈推荐这种写法 ,因为此写法兼容性更好
//像F:\\words他只是在windows支持 在Linux就不识别了  要注意!
String s = "既然选择了远方,便只顾风雨兼程...!";
byte[] b = new byte[1024];
b = s.getBytes();
int length = 0;
fos.write(b);
System.out.println("写入成功!"); 
} catch (Exception e) {
e.printStackTrace();
}finally{
fos.flush();
fos.close();
}
}

//字节输入流  FileInputStream读取文件
@Test
public void testIO2() throws Exception{
FileInputStream fis = null;
try {
fis = new FileInputStream("F:/words.txt");
byte[] b = new byte[1024];//1024kb
  int length = fis.read(b);
  StringBuffer stb = new StringBuffer();
  while (length>0){
fis.read(b); //临时中转站   先将读取的数据保存到byte类型的数组中
stb.append(new String(b));
length = fis.read(b);
}
  System.out.println(stb.toString());
} catch (Exception e) {
e.printStackTrace();
}finally{
fis.close();
}
}

//序列化
@Test
public void testSerializable() throws Exception{
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream("F:/student.txt"));
Student stu = new Student();
stu.setName("张三");
stu.setAge(19);
os.writeObject(stu);
System.out.println("student序列化成功!");//会出现乱码  很正常  因为写入的是二进制字节码文本
}catch (Exception e) {
e.printStackTrace();
}finally{
os.close();
}
}

//反序列化
@Test
public void testSerializable2() throws Exception{
ObjectInputStream ois = null;
ois = new ObjectInputStream(new FileInputStream("F:/student.txt"));
Student stu = (Student)ois.readObject(); //因为该方法返回的是一个object对象,所有必须进行强制类型转换
System.out.println("姓名:"+stu.getName()+"\t年龄:"+stu.getAge());
ois.close();
}
}