FileInputStream \ FileOutputStream的使用
本章是重点!!!后几章介绍的其他流都需要嵌套本章的FileInputStream \ FileOutputStream才能正常使用!!!
(特别适用于非文字类,比如图片/audio/video之类的,但实在想用来传输文字,也能用)
1.执行步骤(注意下面是byte):
- 创建输入流或输出流
- 具体的读入或写出的过程
读入:read(byte[] buffer)
写出:write(byte[] buffer,0,len) - 关闭流资源,避免内存泄漏
2.注意要点:
在注意点的基础上,看其他的注意点。
对于字符流,只能用来操作文本文件,不能用来处理非文本文件。
对于字节流(byte[]),通常是用来处理非文本文件的。但是,如果涉及到文本文件的复制操作,也可以使用字节流。
说明:
文本文件: .txt .java .c .cpp .py等
非文本文件: .doc .xls .jpg .pdf .mp3 .mp4 .avi等
package IOTest;
import org.junit.Test;
import java.io.*;
public class FileReaderWriterTest {
/*
*需求,复制一份test_photo1.jpeg文件,命名为test_photo1_copy.jpeg
*
* */
@Test
public void test06(){
FileInputStream fin = null;
FileOutputStream fout = null;
try {
File f1 = new File("test_photo1.jpeg");
File f2 = new File("test_photo1_copy.jpeg");
fin = new FileInputStream(f1);
fout = new FileOutputStream(f2);
byte [] cart = new byte[1024];
int len = 0;
while(((len=fin.read(cart))!=-1)){
fout.write(cart,0,len);
}
System.out.println("copy job done!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fin != null)
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fout != null)
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
输出为:(图片copy成功)
copy job done!
Process finished with exit code 0