写入文件内容和读取文件内容是对立的;
给文件写入内容:从程序输出,所以用到的类是FileOutputStream、OutputStreamWritter、PrintWritter;
从文件读取内容:给程序输入,所以用到的类是FileInputStream、InputStreamReader、BufferedReader
package JavaTest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.omg.CORBA.PRIVATE_MEMBER;
public class ReadStringFromFileAppMain {
private static final String source_file = "data.txt";
public static void main(String[] args) {
File sourceFile = new File("./"+ source_file);
classicWay(sourceFile);
}
private static void classicWay(File sourceFile) {
try(
//从文件读取byte
FileInputStream input = new FileInputStream(sourceFile);
//将byte用utf_8编码转化成字符或字符串
InputStreamReader isr = new InputStreamReader(input,StandardCharsets.UTF_8);
//将数据读取到buffer,输入输出效率更高,并且可以一次读一行
BufferedReader reader = new BufferedReader(isr);
){
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line.trim().toUpperCase());
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
BufferedReader可以读取1M文件到buffer,提高读取效率;再从buffer中一次可以只读一行;