您的位置:首页 > 编程语言 > Java开发

文章标题 Java中io流的一些简单操作(包含文件复制,向硬盘中写入文本文件,以及io流高级应用序列化和反序列化)

2017-10-30 17:17 856 查看


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 {//注意:要想一个类能够序列化,那个类必须实现Serializable接口
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();
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐