package com.java9.fileCompress;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileIO {
public static void main(String[] args) throws IOException {
String filepath = "/Users/iris/Documents/test/test.txt";
FileIO fileIO = new FileIO();
fileIO.readFile2String(filepath);
}
public void readFile2String(String filepath) throws IOException {
//为了确保文件一定在之前是存在的,将字符串路径封装成File对象
File file = new File(filepath);
if (!file.exists()) {
throw new RuntimeException("要读取的文件不存在");
}
//创建文件字节读取流对象时,必须明确与之关联的数据源
FileInputStream fis = new FileInputStream(file);
//读取 - 将输入流的数据传递给字节数组
//根据流中的字节长度,创建字节数组,保存读到的数据
byte[] contentByte = new byte[fis.available()];
//将字节流中的数据传递给字节数组
fis.read(contentByte);
//将字节数组转为字符串
String s = new String(contentByte);
System.out.println(s);
//关资源
fis.close();
}
}