zoukankan      html  css  js  c++  java
  • 【BigData】Java基础_FileInputStream的基本使用

    概念描述

    知识点1:FileInputStream是按照一个一个字节去文件中读取数据的

    知识点2:当文件中的数据被读取完毕之后,再次读取,则返回的是-1

    知识点3:读取出来的字节可以通过char进行ascII码转换

    代码部分

    test.txt的文件内容如下:

    在以下代码中,为手动去读取一次字节,每read一次,读取一个字节

    package cn.test.logan.day09;
    
    import java.io.FileInputStream;
    
    public class FileInputStreamDemo {
        public static void main(String[] args) throws Exception {
            // 首先构造一个FileInputStream对象
            FileInputStream fis = new FileInputStream("e:/test.txt");
            // FileInputStream是一种字节流,是按照一个一个字节去文件中读取数据的
            int read = fis.read();
            System.out.println(read);        
            
        }
    }

    输出结果为:97

    在上面的代码中我们发现read一次才读取一个字节,并且如果我们一直手工read下去,不难发现,当文件内容被读取完毕之后,则返回-1,所以,我们可以使用-1作为结束标志进行循环读取

    package cn.test.logan.day09;
    
    import java.io.FileInputStream;
    
    public class FileInputStreamDemo {
        public static void main(String[] args) throws Exception {
            // 首先构造一个FileInputStream对象
            FileInputStream fis = new FileInputStream("e:/test.txt");
            // FileInputStream是一种字节流,是按照一个一个字节去文件中读取数据的
            // 根据-1特性,遍历整个文件
            int read = 0;
            while((read = fis.read())!=-1) {
                System.out.println(read);        
            }
            
        }
    }

    输出结果为:97 98 99

    但是在上述读取程序中我们不难发现,这样读取出来的全是"数字",如果需要读取出文件中原模原样的东西,我们必须得转码,以下则为转码程序:

    package cn.test.logan.day09;
    
    import java.io.FileInputStream;
    
    public class FileInputStreamDemo {
        public static void main(String[] args) throws Exception {
            // 首先构造一个FileInputStream对象
            FileInputStream fis = new FileInputStream("e:/test.txt");
            // FileInputStream是一种字节流,是按照一个一个字节去文件中读取数据的
            // 将读取的字节进行转码,使用char
            int read = 0;
            while((read = fis.read())!=-1) {
                char c  = (char)read;
                System.out.println(c);        
            }
            
        }
    }

    输出结果为:a b c

    通过上述程序,我们将文本中的内容完整读取出来了。

  • 相关阅读:
    一直在维护一些项目,其实 这些项目也没有太大的需求,
    iis 7 url 重写
    xmlapp 如何配置
    [转载]什么是native compiler?什么是cross compiler?
    CDC工具
    EDA工具介绍(数字设计)
    让FPGA初学者头疼的各种仿真【转载】
    [SOF] Pointers, smart pointers or shared pointers?
    GNU的工具gmake and make
    mealy machine和moore machine
  • 原文地址:https://www.cnblogs.com/OliverQin/p/12110152.html
Copyright © 2011-2022 走看看