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

public class ByteStreamDemo1 {
    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.FileInputStream;
import java.io.IOException;

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

输出:

1 abcdef123456
``

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

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