流 - FileInputStream

从一个文件按字节读取,输出到控制台

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadFileDemo {
    public static void main(String[] args) {
              
        // 定义一个byte数组准备从文件读取字节
        byte[] buff = new byte[1024];
        // 接受读取的字节数
        int n;
        // 声明一个流
        FileInputStream fis = null;
        try {
            // 实例化流并开始读取
            fis = new FileInputStream(args[0]);
                  
            while((n = fis.read(buff)) != -1 ) {
                // 写入System.out中
                System.out.write(buff, 0, n);
            }
        }   catch (FileNotFoundException e) {
            System.out.print("没有找到文件");
            System.exit(1);
        } catch (IOException e) {
            System.out.print("");
        } finally {
            try {
                // 关闭流
                fis.close();
            } catch (IOException e) {
                System.out.print("文件错误");
                System.exit(1);
            }
        }
    }
}

运行效果

本文出自 “狐灵传说” 博客,转载请与作者联系!

你可能感兴趣的:(static,import,public,控制台)