Java读取文件的四种方式

Java读取文件的四种方式 按字节读取文件内容 按字符读取文件内容 按行读取文件内容 随机读取文件内容    publicclassReadFromFile{/***以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。*/publicstaticvoidreadFileByBytes(StringfileN…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

  1. 按字节读取文件内容

  2. 按字符读取文件内容

  3. 按行读取文件内容

  4. 随机读取文件内容 

     


public class ReadFromFile {
    /**
     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
     */
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容,一次读一个字节:");
            // 一次读一个字节
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        try {
            System.out.println("以字节为单位读取文件内容,一次读多个字节:");
            // 一次读多个字节
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            ReadFromFile.showAvailableBytes(in);
            // 读入多个字节到字节数组中,byteread为一次读入的字节数
            while ((byteread = in.read(tempbytes)) != -1) {
                System.out.write(tempbytes, 0, byteread);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     */
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位读取文件内容,一次读一个字节:");
            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
                // 但如果这两个字符分开显示时,会换两次行。
                // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
                if (((char) tempchar) != '\r') {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("以字符为单位读取文件内容,一次读多个字节:");
            // 一次读多个字符
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // 读入多个字符到字符数组中,charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 同样屏蔽掉\r不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != '\r')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '\r') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容,一次读一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 随机读取文件内容
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("随机读取一段文件内容:");
            // 打开一个随机访问文件流,按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 读文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
            // 将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 显示输入流中还剩的字节数
     */
    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前字节输入流中的字节数为:" + in.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String fileName = "C:/temp/newTemp.txt";
        ReadFromFile.readFileByBytes(fileName);
        ReadFromFile.readFileByChars(fileName);
        ReadFromFile.readFileByLines(fileName);
        ReadFromFile.readFileByRandomAccess(fileName);
    }
}

 5.  将内容追加到文件尾部

public class AppendToFile {
    /**
     * A方法追加文件:使用RandomAccessFile
     */
    public static void appendMethodA(String fileName, String content) {
        try {
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            //将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * B方法追加文件:使用FileWriter
     */
    public static void appendMethodB(String fileName, String content) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String fileName = "C:/temp/newTemp.txt";
        String content = "new append!";
        //按方法A追加文件
        AppendToFile.appendMethodA(fileName, content);
        AppendToFile.appendMethodA(fileName, "append end. \n");
        //显示文件内容
        ReadFromFile.readFileByLines(fileName);
        //按方法B追加文件
        AppendToFile.appendMethodB(fileName, content);
        AppendToFile.appendMethodB(fileName, "append end. \n");
        //显示文件内容
        ReadFromFile.readFileByLines(fileName);
    }
}

原文出处:http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/159340.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • LaTeX多行公式_latex大括号左对齐

    LaTeX多行公式_latex大括号左对齐LaTeX是一种基于ΤΕΧ的排版系统,其中非常突出的是方便而强大的数学公式排版能力。XMind2020现已支持插入LaTeX数学命令,可实时转化为数学方程。此外还支持部分简单的化学方程,理工科的朋友们从此无需再借助其它应用,在XMind中即可完成方程的输入。今天和大家分享下在XMind中如何用LaTeX输入数学公式。1.插入方程在「插入菜单」中找到方程,点击即可进入方程…

    2022年10月11日
    4
  • 2021DIY电脑配置入门篇(包含各cpu显卡天梯图对比)

    2021DIY电脑配置入门篇(包含各cpu显卡天梯图对比)前言:我本来以为一篇文章可以把电脑配置讲清楚的,但是发现电脑比我想象的要复杂,所以可能分了几篇来写如何查看自己的电脑配置最简单的右键桌面此电脑->点击属性下载个电脑管家等电脑助手软件也可以查看详细配置如何DIY自己的第一台电脑篇幅有限,这里我只详细分析一台电脑的核心配置(CPU、主板、显卡),外加内存定好预算对于电脑来说,预算是最重要的!没有预算,一切都是空谈。没预算默认外星人Area51M(价格在2万左右),现在电脑往往充当一种娱乐需求,相对来说比较次要,因此大多数人配电脑.

    2022年7月12日
    31
  • 查询linux版本信息的命令_查系统版本命令

    查询linux版本信息的命令_查系统版本命令通常使用命令uname在Linux下面察看版本信息-a或–all:显示全部的信息;-m或–machine:显示电脑类型;-n或-nodename:显示在网络上的主机名称;-r或–release:显示操作系统的发行编号;-s或–sysname:显示操作系统名称;-v:显示操作系统的版本;-p或–processor:输出处理器类型或”unknown”;-i或-

    2022年8月21日
    8
  • 使用Python暴力激活成功教程密码

    使用Python暴力激活成功教程密码由于业务需求,今天项目对接了百度云智能的风控系统,注册和登陆保护,想来测试一下性能,用python写了一个脚本,暴力激活成功教程密码,看看会不会触发风控一、首先在本地新建了一个数据库,保存已经试错过的密码CREATETABLE`test`.`pwd`(`id`int(10)NOTNULLAUTO_INCREMENT,`passwod`varchar(20)CHARACTERSETutf8COLLATEutf8_general_ciNOTNULLDEFAULT’…

    2022年8月22日
    11
  • vivado2018.3 安装(包含license)

    vivado2018.3 安装(包含license)Xilinx采用的是ISE和vivado;Altera采用的是quartusII。vivado2018.3安装本次安装问题描述:(1)上一次上官网下的比较慢,官网链接:https://china.xilinx.com/support/download/index.html/content/xilinx/zh/downloadNav/vivado-design-tools.html…

    2022年7月26日
    68
  • executenonquery报错_sql2008和mysql

    executenonquery报错_sql2008和mysqlExecuteNonQuery()方法主要用户更新数据,通常它使用Update,Insert,Delete语句来操作,其方法返回值意义:对于Update,Insert,Delete语句执行成功是返回值为该命令所影响的行数,如果影响的行数为0时返回的值为0,如果数据操作回滚得话返回值为-1,对于这种更新操作用我们平时所用的是否大于0的判断操作应该没有问题而且比较好,但是对于其他的操作如对数据…

    2025年10月30日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号