龙哥网

龙哥网

使用FileInputStream读取文件内容(fileoutputstream读取文件)
2022-03-01

代码如下:

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();
}
}
}
}

运行结果如下: 


免责声明
本站部分资源来源于互联网 如有侵权 请联系站长删除
龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。