使用FileInputStream读取文件内容

版权声明:本文为博主原创文章,如需转载请务必添加原文地址! https://blog.csdn.net/qq_35661171/article/details/86538982

废话不多说, 直接上关键代码

package com.zhongjing.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FileInputStreamDemo {

    /**
     * FileInputStream 字节输入流 --> 读取数据
     * @param args
     */
    public static void main(String[] args) {
        FileInputStream fis = null;
        File file = new File("D:/test.txt");
        try {
            fis = new FileInputStream(file);
            byte[] buf = new byte[1024]; //数据中转站 临时缓冲区
            int length = 0;
            //循环读取文件内容,输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
            //当文件读取到结尾时返回 -1,循环结束。
            while((length = fis.read(buf)) != -1){
                System.out.println(new String(buf, 0, length));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fis.close();//强制关闭输入流
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
    }
}
运行结果如下: 

关于怎样使用FileOutStream写入内容请查看下面这篇文章 : 

https://blog.csdn.net/qq_35661171/article/details/86539554

猜你喜欢

转载自blog.csdn.net/qq_35661171/article/details/86538982