字节流需要用到的类:
字符流需要用到的类:
说一下读写操作大致过程:
一般如果纯文本,我们最好用字符流,但是如果图片,这种按照字节拼接,就采用字节流
下面看一下代码实例:我们从一张盘拷贝一张照片到另外一张盘
import java.io.*;
public class ImageCopy {
public static void main(String[] args) {
File srcFile = new File("F:\\pxx\\1.jpg");
File destFile = new File("E:\\haha.jpg");
copyImage(srcFile,destFile);
}
//这个采用一边读,一边写的思路来做
public static void copyImage(File srcFile, File destFile) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buff = new byte[1024];
int len = 0;
while((len = fis.read(buff)) != -1) {
fos.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
然后我们看一下对于一个文本拷贝的代码:关于乱码问题,可以看一下我字符集编码问题:
//采用字符流来读取文本操作
public static void copyText(File srcFile,File destFile) {
InputStreamReader fr = null;
OutputStreamWriter fw = null;
try {
fr = new InputStreamReader(new FileInputStream(srcFile),"gbk");
// fw = new FileWriter(destFile);
fw = new OutputStreamWriter(new FileOutputStream(destFile),"gbk");
char[] buff = new char[1024];
int len = 0;
while((len = fr.read(buff)) != -1) {
System.out.println("读取到的长度:" + len);
fw.write(buff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ByteArrayOutputStream与ObjectOutputStream
它的父类是OutputStream输出字节流,也就是下面方法都可以用
该类实现了将数据写入字节数组的输出流。数据可以使用toByteArray()变成字节数组或者变成字符串toString()
在java中,ByteArrayOutputStream是一个内存输出流,它不涉及底层文件或网络资源,因此不需要显示关闭。使用完ByteArrayOutputStream之后,我们可以直接获取其内部的字节数组,关闭这个流不会有任何影响
ObjectOutputStream是java中的一个输出流,它也是OutputStream流的子类,作用是将java对象序列化为字节流,以便于保存到文件,发送到网络或者在内存中传递
上面是放到了一个网络的字节流里面 ,当然我们也可以不放到网络字节流里面,放到本地文件里面
大致说一下网络序列化流程
这个输入流里面需要传入一个字节数组