0x01 目录结构
# 目录结构├── FileReadTest│ ├── FileInputStreamTestReadDemo.java│ ├── FileReaderTestReadDemo.java│ ├── FilesTestReadDemo.java│ ├── RandomAccessFileTestReadDemo.java
0x02 相关例子
0x02.1 FileInputStream
// 文件名: FileInputStreamTestReadDemo.javapackage FileReadTest;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;public class FileInputStreamTestReadDemo {public static void main(String[] args) {// 要读取的文件File f = new File("/etc/hosts");FileInputStream fis = null;try {// 打开文件对象并创建文件输入流fis = new FileInputStream(f);// 定义每次 输入流 读取到的字节数int l;// 定义缓冲区大小byte[] bytes = new byte[1024];// 创建二进制输出流对象ByteArrayOutputStream out = new ByteArrayOutputStream();// 循环读取文件内容while ((l = fis.read(bytes)) != -1) {// 截取缓冲区数组中的内容// 下标0开始截取,l 表示每次输入流读取到的字节数。out.write(bytes, 0, l);}// 输出读取到的内容System.out.println(out.toString());} catch (Exception e) {e.printStackTrace();} finally {try {// 强制关闭输入流fis.close();} catch (IOException e) {e.printStackTrace();}}}}
0x02.2 FileReader
// 文件名: FileReaderTestReadDemo.javapackage FileReadTest;import java.io.FileReader;import java.io.IOException;public class FileReaderTestReadDemo {public static void main(String[] args) {FileReader fr = null;try {// 打开文件对象fr = new FileReader("/etc/hosts");// 定义每次 输入流 读取到的字节数int l;// 定义缓冲区大小char[] buf = new char[6];// 用与保存读取文件内容的StringBuilder out = new StringBuilder();// 循环读取文件内容while((l = fr.read(buf)) != -1){String str = new String(buf, 0, l);out.append(str);}// 输出读取到的内容System.out.print(out);} catch (Exception e) {e.printStackTrace();} finally {try {// 强制关闭输入流fr.close();} catch (IOException e) {e.printStackTrace();}}}}
�
0x02.3 Files
// 文件名: FilesTestReadDemo.javapackage FileReadTest;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;public class FilesTestReadDemo {public static void main(String[] args) {// 要读取的文件Path path = Paths.get("/etc/hosts");try {byte[] bytes = Files.readAllBytes(path);String out = new String(bytes);System.out.println(out);} catch (Exception e) {e.printStackTrace();}}}
0x02.4 RandomAccessFile
// 文件名: RandomAccessFileTestReadDemo.javapackage FileReadTest;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;public class RandomAccessFileTestReadDemo {public static void main(String[] args) {// 要读取的文件File f = new File("/etc/hosts");RandomAccessFile raf = null;try {// 创建 RandomAccessFile对象// 共有:// r(只读)、rw(读写)、rws(读写内容同步)、rwd(读写内容或元数据同步) 模式打开文件raf = new RandomAccessFile(f, "r");// 定义每次 输入流 读取到的字节数int l;// 定义缓冲区大小byte[] bytes = new byte[1024];// 创建二进制输出流对象ByteArrayOutputStream out = new ByteArrayOutputStream();// 循环读取文件内容while ((l = raf.read(bytes)) != -1) {// 截取缓冲区数组中的内容// 下标0开始截取,l 表示每次输入流读取到的字节数。out.write(bytes, 0, l);}// 输出读取到的内容System.out.println(out.toString());} catch (Exception e) {e.printStackTrace();} finally {try {// 强制关闭输入流raf.close();} catch (IOException e) {e.printStackTrace();}}}}
