IO流(2)FileInputStream
package IO.inputstream; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class FileInputStream { public static void main(String[] args) { } /** * 演示FileInputStream的使用(字节输入流 文件-->程序) * @author 长空扯淡 */ @Test public void readFile01(){ String filePath = "e:\\hello.txt"; int readDate = 0; java.io.FileInputStream fileInputStream = null; try { //创建FileInputStream对象,用来读取文件 fileInputStream = new java.io.FileInputStream(filePath); //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止 //如果返回-1,表示读取完毕 while((readDate = fileInputStream.read())!=-1){ System.out.print((char)readDate);//转成char显示 } } catch (IOException e) { e.printStackTrace(); } finally { //关闭文件流,释放资源 try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 使用read(byte[] b)//读取文件,提高效率 * @author 长空扯淡 */ @Test public void readFile02(){ String filePath = "e:\\hello.txt"; int readLen = 0; //字节数组 byte[] buf = new byte[10];//一次读取8个字节 java.io.FileInputStream fileInputStream = null; try { //创建FileInputStream对象,用来读取文件 fileInputStream = new java.io.FileInputStream(filePath); //从该输入流读取最多b.length字节的数据到字节数组。此方法将阻塞,直到某些输入可用 //如果返回-1,表示读取完毕 //如果读取正常,返回实际读取的字节数 while((readLen = fileInputStream.read(buf))!=-1){ System.out.print(new String(buf,0,readLen));//转成char显示 } } catch (IOException e) { e.printStackTrace(); } finally { //关闭文件流,释放资源 try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本