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);
    }
}

java读取文件多种方法的更多相关文章

  1. [Java]读取文件方法大全(转)

    [Java]读取文件方法大全   1.按字节读取文件内容2.按字符读取文件内容3.按行读取文件内容 4.随机读取文件内容 public class ReadFromFile {     /**     ...

  2. Java读取文件-BufferedReader/FileReader/InputStreamReader/FileInputStream的关系和区别

    一.Java读取和存储文件数据流 Java读取文件,实际是将文件中的字节流转换成字符流输出到屏幕的过程   这里面涉及到两个类:InputStreamReader和OutputStreamWriter ...

  3. 分享:Perl打开与读取文件的方法

    在Perl中可以用open或者sysopen函数来打开文件进行操作,这两个函数都需要通过一个文件句柄(即文件指针)来对文件进行读写定位等操作. Perl打开与读取文件的方法,供大家学习参考.本文转自: ...

  4. Java 读取文件的内容

    Java 读取文件的内容 1) CLASS_NAME: 换成自己真实的类名 2) /page/test.json: 换成自己真实的page 3) FileUtils: 来自于org.apache.co ...

  5. Python读取文件基本方法

    在日常开发过程中,经常遇到需要读取配置文件,这边就涉及到一个文本读取的方法. 这篇文章主要以Python读取文本的基础方法为本,添加读取整篇文本返回字符串,读取键值对返回字典,以及读取各个项返回列表的 ...

  6. Java读取文件方法和给文件追加内容

    本文转载自:http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html 1.按字节读取文件内容2.按字符读取文件内容3.按行读取文 ...

  7. java读取文件方法总结

    由于最近在做一个关于从手机本地读取格式化的txt文件中的内容,并且把内容放在listview中显示.这样问题来了,就是如何能够遍历已经获取到特定的map中就是一个问题,在网上找了一些资料,找到了一个很 ...

  8. asp.net读取excel文件多种方法

    asp.net读取excel文件的三种方法示例,包括采用OleDB读取Excel文件.引用的com组件读取Excel文件.用文件流读取.   方法一:采用OleDB读取Excel文件 把Excel文件 ...

  9. 【转】Java读取文件方法大全

    本文转自:http://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html#undefined 目录: 按字节读取文件内容 按字符读取文 ...

随机推荐

  1. 机器学习实战5:k-means聚类:二分k均值聚类+地理位置聚簇实例

    k-均值聚类是非监督学习的一种,输入必须指定聚簇中心个数k.k均值是基于相似度的聚类,为没有标签的一簇实例分为一类. 一 经典的k-均值聚类 思路: 1 随机创建k个质心(k必须指定,二维的很容易确定 ...

  2. XAMPP和Bugfree详细教程

    一.XAMPP安装配置 xampp是一款跨平台的集成 apache + mysql + php环境,是的配置AMP服务器变得简单轻松,支持windows,solaris, 下载地址:http://so ...

  3. python False

    None 空字符串 空列表 空元组 空字典 false为False

  4. ubuntu使用记录

    常用指令 ls        显示文件或目录 -l           列出文件详细信息l(list) -a          列出当前目录下所有文件及目录,包括隐藏的a(all) mkdir     ...

  5. Android 标签的主题样式

    Android平台定义的主题样式: android:theme="@android:style/Theme.Dialog"   将一个Activity显示为对话框模式 •andro ...

  6. 探秘腾讯Android手机游戏平台之不安装游戏APK直接启动法

    前言相信这样一个问题,大家都不会陌生,“有什么的方法可以使Android的程序APK不用安装,而能够直接启动”.发现最后的结局都是不能实现这个美好的愿望,而腾讯Android手机游戏平台却又能实现这个 ...

  7. 【PHP设计模式 02_JieKou.php】面向接口开发

    <?php /** * [面向接口开发] * */ header("Content-type: text/html; charset=utf-8"); /*共同接口--连接数 ...

  8. PostgreSQL的 Slony-I 数据同步

    原文--http://www.tuicool.com/articles/mMvARf 先谈谈slony的局限性: 1. DDL动作是不会被复制到: 2. 如果想使用slony来同步数据,表必须是带有主 ...

  9. JS删除script标签

    可以试试以下方法 var deleteJs = document.getElementById('xxx'); var otherJs = document.getElementsByTagName( ...

  10. Python学习笔记-Day2-Python基础之元组操作

    元组的常用操作包括但不限于以下操作: 元组的索引,计数等 这里将对列表的内置操作方法进行总结归纳,重点是以示例的方式进行展示. 使用type获取创建对象的类 type(tuple) 使用dir获取类的 ...