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.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if (!myFolderPat ...

  2. JAVA文件读取FileReader

    JAVA文件读取FileReader 导包import java.io.FileReader 创建构造方法public FileReader(String filename),参数是文件的路径及文件名 ...

  3. Java文件读取

    package a.ab; import java.io.*; public class FileWrite { public static void main(String[] args) { Fi ...

  4. Java文件操作大全

    //1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if (!myFolderPath.exists()) ...

  5. java文件读取与写入

    package com.myjava; import java.io.*; import java.util.ArrayList; import java.util.Collections; impo ...

  6. 【转】java 文件 读取目录下的所有文件(包括子目录)

    转自:http://www.cnblogs.com/pricks/archive/2009/11/11/1601044.html import java.io.File; import java.io ...

  7. java 文件读取的一些方法

    web项目读取日志文件 //得到路径 String appPath = filterConfig.getServletContext().getRealPath("/"); // ...

  8. JAVA 文件读取写入后 md5值不变的方法

    假如我们想把某文件读入 StringBuffer 并写入新文件,新文件md5值需要保持不变(写入新文件后保证和源文件一模一样), 我们就需要在操作 StringBuffer 时附加换行符: Strin ...

  9. 【转】java文件操作大全

    一.获得控制台用户输入的信息 public String getInputMessage() throws IOException...{         System.out.println(&qu ...

随机推荐

  1. iOS app上传错误集锦(转载)

    1.工程里增加了版本自动更新. 2.未增加判断网络状态的类Reachability. 3.问题:error itms -90049 This bundel is invalid. The bundle ...

  2. onmeasure

    UNSPECIFIE : 0 [0x0],未加规定的,表示没有给子view添加任何规定. EXACTLY : 1073741824 [0x40000000],精确的,表示父view为子view确定精确 ...

  3. ab压测&htop工具

    1,apache bech 参考: http://www.nginx.cn/110.html http://www.ha97.com/4617.html ===================== y ...

  4. Quartz.net打造信息抽取器

    由于最近的一个项目需要定时抽取特定XML信息,然后保存到数据库,最后通过WebApi把手机端要使用的方法给暴露出来,所以去研究了一下Quartz.net.由于项目很小,我没用到Autofac,Repo ...

  5. Java从0开始学——字符串

    #,java中的字符串是不可变的: #,比较两个字符串是不是相等,不能用==,因为那只能确认他们是否指向了同一个字符串对象: #,空串和null是不同的: #,代码点和代码单元     #,代码点表示 ...

  6. gdb学习

    gdb学习 [参考资料] http://www.cnblogs.com/jiu0821/p/4483804.html 程序的运行状态有"运行"."暂停".&qu ...

  7. 【面试必备】Swift 面试题及其答案

    初级 问题1- Swift 1.0 or later 什么是optional类型,它是用来解决什么问题的? 答案:optional类型被用来表示任何类型的变量都可以表示缺少值.在Objective-C ...

  8. model的封装+MJExtension 方便后续处理

    //  基本模型 #import <Foundation/Foundation.h> @interface BasicDataModel : NSObject - (id)initWith ...

  9. brew-cask之本地安装应用

    cask 固然好用,但是无奈很多资源在墙外,能下载的非常有限,就是能下载,也慢的要死.但是很多下载软件却可以下载这些资源,很奇怪,要么是有人FQ下载了,缓存到他们的服务器了,要么就是软件可以FQ下载. ...

  10. web安全——简介

    简介 不对外提供服务是最安全的. 安全是基于信任.如果信任失败了,则没有安全.比如你给一个ip加白名单,结果这个ip对你发动了安全攻击. 在非常明确需要提供服务的时候才对外提供服务,即白名单.其他的全 ...