写在前面: 我是「扬帆向海」,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。
技术是开源的、知识是共享的。
这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。
用知识改变命运,让我们的家人过上更好的生活
。
前面的博客介绍了把文件中的内容读入程序中并打印到控制台和把数据从内存写出到磁盘中。这篇文章算是对节点流读写操作的综合!
对于 文本文件 使用 字符流 进行处理
比如:.txt, .java 等
对于 非文本文件 使用 字节流 进行处理
比如 .doc, .excel, .ppt, .jpj, .mp3, .avi 等
一、文本文件的操作
操作步骤
- 实例化File 对象,读入文件、写出文件
- 实例化输入流和输出流
- 创建一个临时存放数据的char型数组
- 当读入的字符个数存在时进行写出操作
- 关闭流资源
将当前工程下面的111.txt 文本文件复制到 222.txt
代码实现
/**
* 实现对文件的复制操作
*/
public class FileReaderWriterTest {
public static void main(String[] args) {
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
// 实例化File对象,读入的文件
File srcFile = new File("111.txt");
// 实例化File对象,写出的文件
File destFile = new File("222.txt");
// 实例化输入流和输出流
fileReader = new FileReader(srcFile);
fileWriter = new FileWriter(destFile);
// 数据的读入和写出操作
// 创建一个临时存放数据的char型数组
char[] chars = new char[5];
// 每次读入到chars数组中的字符个数
int length;
// 当读入的字符个数存在时进行写出操作
while ((length = fileReader.read(chars)) != -1) {
fileWriter.write(chars, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流资源
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二、非文本文件的操作
将当前工程下面的 Lighthouse.jpg 复制到 Lighthouse1.jpg
代码实现
/**
* 图片的复制
*/
public class FileReadWriterTest1 {
public static void main(String[] args) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
// 实例化File对象
File srcFile = new File("Lighthouse.jpg");
File destFile = new File("Lighthouse1.jpg");
// 实例化输入流和输出流
inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(destFile);
// 数据的读入和写出操作
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流资源
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}