https://blog.csdn.net/fight_man8866/article/details/80736657
一、使用字节流读取
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test08 {
public static void main(String[] args) {
// 1.定义目标文件
File srcFile = new File("E:/Temp/Test1.txt");
// 2.创建一个流,指向目标文件
InputStream is = null;
try {
is = new FileInputStream(srcFile);
//3.创建一个用来存储读取数据的缓冲数组
byte[]array = new byte[128];
//4.循环往外流(count为每次读取数组中的有效字节总数)
int count = is.read(array);
// 5.循环打印
while (count != -1) {
// 将byte[] -》 String
// 将byte数组读取到的有效字节转换成字符串
String string = new String(array, 0, count);
System.out.print(string);
count = is.read(array);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭io流
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二、使用字符流读取
package com.uwo9.test01;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class Test08 {
public static void main(String[] args) {
// 1.创建文件对象
File fromFile = new File("E:/Temp/Test1.txt");
// 2.创建字符输入流
Reader reader = null;
try {
reader = new FileReader(fromFile);
// 3.循环读取(打印)
int content = reader.read();
while (content != -1) {
System.out.print((char) content);
content = reader.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
// 4.关闭流
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}