IO流——文件操作流之字节输入流FileInputStream

    xiaoxiao2025-07-28  5

    package com.io.ioDemo; /**为什么要手动的关闭IO流? * 因为程序中打开的io流不属于内存当中的资源,所以垃圾回收机制就无法回收,所以就要显示关闭io流。 * */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; //问题:文件里的中文会乱码 public class FileInputStreamDemo { public static void main(String[] args) { FileInputStream fis = null; try { //1创建文件字节输入流 fis = new FileInputStream(new File("c:\\fis.txt")); //2创建用于存储字节的数组 byte[] bt = new byte[1024]; //3创建int型变量,用来表示读入的字节数 int hasread = 0; StringBuffer sb = new StringBuffer(); //4循环获取数据 while((hasread = fis.read(bt))!=-1){ //5把字节数组转换成字符串输出 sb.append(new String(bt,0,hasread)); } System.out.println(sb); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { //6关闭输入流 if(fis!=null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
    转载请注明原文地址: https://ju.6miu.com/read-1301168.html
    最新回复(0)