结论:
- 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
- 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理
如果只是复制文本文件,字节流可以完成,字节流相当于搬运工不会去看,如果在内存层面去读会出现乱码
while((len = fr.read(cbuf)) != -1){
String str = new String(cbuf,0,len);
System.out.print(str);
// for(int i = 0;i < len;i++){
// System.out.print(cbuf[i]);
// }
}
读取文本还是得用字符流
public class StreamTest02 {
@Test
public void Test(){//文件复制操作
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
//读入文件写出文件创建
File srcfile = new File("hello.txt");
File descfile = new File("helloCopy.txt");
//输入流输出流
fileReader = new FileReader(srcfile);
fileWriter = new FileWriter(descfile,false);
//true不覆盖文件descfile,在descfile文件下继续写入,false覆盖文件旧的 descfile文件
//把文件hello.txt的文件读取出来直接写出到新文件helloCopy.txt,就完成了文件内容的复制
char[] charTest = new char[5];
int len;
//把hello.txt的文件内容读取到charTest数组,因为容量为5,一次只能存入五个字符
while ((len = fileReader.read(charTest)) != -1){
//将每次存入的5个字符直接写出到文件helloCopy.txt,通过写出流write方法
fileWriter.write(charTest,0,len);
}
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if (fileReader != null){
try {
//判断是否为空才能关闭流,否则会报空指针异常 NullPointException
fileReader.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
//第二个try/catch可以放到第一个try/catch 的finally里
//也可以不放finally,因为try/catch完下面代码是会执行的,因为已经把异常catch掉了
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
//使用字节流复制图片
@Test
public void fileInputOutputStreamTest(){
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
File jpgFile = new File("f6330d141cf7324e310ea5e481b56e11--2979603408.jpg");
File jpgFileCopy = new File("f6330d141cf7324e310ea5e481b56e11--297960340802.jpg");
//System.out.println(jpgFile.getAbsoluteFile());
fileInputStream = new FileInputStream(jpgFile);
fileOutputStream = new FileOutputStream(jpgFileCopy);
byte[] bytes = new byte[5];//字节流所有创建byte[]
int len;
while((len = fileInputStream.read(bytes)) != -1){
fileOutputStream.write(bytes,0,len);
}
System.out.println("图片复制成功");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
if (fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
if (fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
}



