文章目录
- File的IO操作
- 一、FileReader(读取字符文件)的使用
-
- 二、FileWriter(写出字符文件)的使用
- 三、FileInputStream(读取字节文件)与fileOutputStream(写出字节文件)的使用
- 四、总结
File的IO操作
一、FileReader(读取字符文件)的使用
(一)一次读一个字符
@Test
public void test() {
FileReader fileReader = null;
try {
//1、实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");
//2、提供具体的流
fileReader = new FileReader(file);
//3、数据的读入
//read():返回读入的一个字符,如果达到文件末尾,返回-1
//方式一
//方式二
int data;
while ((data = fileReader.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4、流的关闭操作
try {
if(fileReader != null){
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
(二)一次读多个字符
//对read()操作升级:使用read的重载方法
@Test
public void test2() {
FileReader fileReader = null;
try {
//1、File类的实例化
File file = new File("hello.txt");
//2、FileReader流的实例化
fileReader = new FileReader(file);
//3、读入操作
char[] cbuf = new char[5];
int len;
//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数,如果达到文件末尾返回-1
while ((len = fileReader.read(cbuf)) != -1) {
for (int i = 0; i < len; i++) {
System.out.print(cbuf[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4、资源的关闭
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、FileWriter(写出字符文件)的使用
@Test
public void writer() {
FileWriter fileWriter = null;
try {
//1、提供File类的对象,指明写出到的文件
File file = new File("hello.txt");
//2、提供FileWriter的对象,用于数据的写出
//true表示在原有文件上追加,默认为false
fileWriter = new FileWriter(file, true);
//3、写出操作
fileWriter.write("I have dream");
fileWriter.write("You have dream");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileWriter != null) {
//4、流资源的关闭
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、FileInputStream(读取字节文件)与fileOutputStream(写出字节文件)的使用
@Test
public void fileStreamTest() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
//1、造文件
File file = new File("搜狗截图20211116110950.png");
File copy = new File("copy.png");
//2、造流
fileInputStream = new FileInputStream(file);
fileOutputStream = new FileOutputStream(copy);
//3、读取
byte[] buffer = new byte[5];
int len;
while ((len = fileInputStream.read(buffer)) != -1) {
//4、写出数据
fileOutputStream.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4、关闭流
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
四、总结
- 字符文件用字符流(.txt .doc等)
- 字节文件用字节流(.mp3 .mp4等)