字节流(2字节 = 8bit)
输入:InputStream
输出:OutputStream
字符流(4字节 = 16bit)
输入:Reader
输出:Writer
处理文本用字符流,处理媒体文件用字节流
字节流处理文本:字节流一次读2个字节,而一个中文占用3个字节(对copy文件没有影响),对Console显示会出现乱码问题
对象流与序列化
什么是序列化:序列化就是一种用来处理对象流的机制,对象流也就是将对象的内容进行流化,将数据分解成字节流,以便存储在文件中或在网络上传输
被static或transient修饰的成员变量不能序列化
实现 Serializable接口 与
编写private static final long serialVersionUID = -12123123L;
class Students implements Serializable{
private static final long serialVersionUID=1213123121212L;
String name;
int age;
public Students(String name, int age) {
this.name = name;
this.age = age;
}
}
序列化与反序列化
/**
* 可以通过网络传播或保存在本地磁盘上
*/
序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
oos.writeObject(new Students("solo",12));
反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.txt"));
Students student = (Students) ois.readObject();
随机存储文件流
r:只读;rw:读取写入;rwd:读取写入,同步文件内容更新;rwds:读取写入,同步文件内容更新和元数据更新
初始化方式 1:
new RandomAccessFile("filePath","rw");
初始化方式 2:
new RandomAccessFile(new File("filePath"),"rw");
重要的两个方法
public native long getFilePointer() 获取文件记录指针的读取位置
public void seek(long pos) 将指针定位到pos位置
转换流(属于字符流)
FileInputStream fis = new FileInputStream(new File(""));
FileOutputStream fos = new FileOutputStream(new File(""));
1).输入字节流转字符流
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
2).输出字节流转字符流
OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
文件的简单加密与解密
加密 与 解密
//encryption and decryption
public void encryption(String source,String target) throws Exception{
//造文件
File file = new File(source);
File encryption = new File(target);
//造流
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(encryption);
//造缓冲流
BufferedInputStream bis = new BufferedInputStream(fileInputStream);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//加密或解密输出
byte[] buff=new byte[1024*2];
int len;
while((len=bis.read(buff)) != -1){
for(int i=0;i<len;i++){
buff[i]=(byte)(buff[i]^5);
}
bos.write(buff,0,len);
}
}
------------------END------------------