字节流需要用到的类:
字符流需要用到的类:
说一下读写操作大致过程:
一般如果纯文本,我们最好用字符流,但是如果图片,这种按照字节拼接,就采用字节流
下面看一下代码实例:我们从一张盘拷贝一张照片到另外一张盘
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();
}
}
}
}