1. 使用字节输入流一次读取一个字节的方法将file01.txt的文件读取并打印
import java.io.*;

public class ReadFile {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("D:/file01.txt");
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char)data);
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出结果:1 abcdef123456

  1. 使用字节输入流一次读取多个字节的方法将file01.txt的文件读取并打印
import java.io.*;

public class ReadFile {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("D:/file01.txt");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, len));
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出结果:1 abcdef12345


原文地址: https://www.cveoy.top/t/topic/frN5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录