IO流基本操作

1.File类的实例化
2.FileReader流的实例化
3.读入的操作
4.资源的关闭

read():返回读入的一个字符。如果达到文件末尾,返回-1

不能使用字符流来处理图片等字节数据

测试FileInputStream和FileOutputStream的使用
对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字节流处理
使用字节流FileInputStream处理文本文件,可能出现乱码。

图片复制操作示例代码

/*
实现对图片的复制操作
*/
@Test
public void testFileInputOutputStream() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//
File srcFile = new File("爱情与友情.jpg");
File destFile = new File("爱情与友情2.jpg");

//
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);

//复制的过程
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
fos.write(buffer,0,len);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
//
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}


//
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);

//复制的过程
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
fos.write(buffer,0,len);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
//
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
}

posted @ 2022-04-19 15:47  93丶Fss  阅读(40)  评论(0)    收藏  举报