• 【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

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

  • 相关阅读:
    一套完整的javascript面试题
    遇到的java.lang.NoClassDefFoundError解决了
    Win7下启动Internet信息服务(IIS)管理器
    我的第一个专业博客
    “用NetBeans打开项目时项目名变成红色”问题解决
    Struts2框架实现计算器功能
    MyEclipse移动包到另一个项目时出现错误:Resource is out of sync with the file system.
    制作Javascript弹出窗口技巧九则
    windows 的鼠标事件(Event)
    Javascript使用cookie
  • 原文地址:https://www.cnblogs.com/OliverQin/p/12110152.html
Copyright © 2020-2023  润新知