Java InputStream如何读取文件呢?

转自:

Java InputStream如何读取文件呢?

下文笔者将讲述InputStream读取文件的方法分享,如下所示:

FileInputStream通过文件byte数组暂存文件中内容
将其转换为String数据
再根据“回车换行” 进行分割

public static String[] readToString(String filePath) {
    File file = new File(filePath);
    Long filelength = file.length(); // 获取文件长度
    byte[] filecontent = new byte[filelength.intValue()];
    try {
        FileInputStream in =new FileInputStream(file); in .read(filecontent); in .close();
    } catch(FileNotFoundException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    }

    String[] fileContentArr = new String(filecontent).split("\r\n");

    return fileContentArr; // 返回文件内容,默认编码
}

使用InputStream从文件里读取数据,在已知文件大小的情况下,建立合适的存储字节数组

public class TestClass {
    public static void main(String args[]) throws Exception {
        File f = new File("E:" + File.separator + "test" + File.separator + "StreamDemo" + File.separator + "java265.txt");
        InputStream in =new FileInputStream(f);
        byte b[] = new byte[(int) f.length()]; //创建合适文件大小的数组
        in .read(b); //读取文件里的内容到b[]数组
        in .close();
        System.out.println(new String(b));
    }
}

使用InputStream从文件里读取数据
当不知道文件大小时,可循环读取文件

public static void main(String args[]) throws Exception {
    File f = new File("E:" + File.separator + "test" + File.separator + "StreamDemo" + File.separator + "java265.txt");
    InputStream in =new FileInputStream(f);
    byte b[] = new byte[1024];
    int len = 0;
    int temp = 0; //全部读取的内容都使用temp接收
    while ((temp = in.read()) != -1) { //当没有读取完时,继续读取
        b[len] = (byte) temp;
        len++;
    } in .close();
    System.out.println(new String(b, 0, len));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值