美文网首页
JAVA IO流读写操作

JAVA IO流读写操作

作者: minminaya | 来源:发表于2017-04-01 17:46 被阅读194次

目录

  • 读涉及到的API
  • 创建一个最普通的读文件操作
  • 读取文件方法大全
  • 复制文件(输出流)
  • 高效的RandomAccessFile

读涉及到的API

  1. File
  2. InputStream
  3. FileInputStream
  4. InputStreamReader(编码转换桥梁)
  5. BufferedReader(缓冲,提高速度)

与之对应的是输出流,大致相通

  1. OutputStream
  2. FileOutputStream
  3. OutputStreamWriter
  4. BufferedWriter

注:全局序号

先去了解文档,传送阵---->JDK 1.6 中文版

  • 需要了解12345五个类的构造函数
  • 继承关系(下面有图)
  • 一些read readline 方法
InputStream继承关系 InputStreamReader BufferedReader

可以看到BufferedReader与InputStreamReader都是Reader的子类(关键

创建一个最普通的读文件操作

读取一个lrc歌词文件

private void readLrc() {
        //F盘根目录下有一个海阔天空.lrc文件,注意这里的转义符
        File file = new File("F:\\海阔天空.lrc");
        InputStream in = null;
        
        try {
            in = new FileInputStream(file);
            int position ;//读取位置
            while((position = in.read()) != -1){
                System.out.write(temp);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            in.close();//关闭输入流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

输出结果

[02:15.26]涔熶細鎬曟湁涓?澶╀細璺屽??
[02:21.41]鑳屽純浜嗙悊鎯? 璋佷汉閮藉彲浠?
[02:27.56]鍝細鎬曟湁涓?澶╁彧浣犲叡鎴?
[02:33.38]
[03:08.48]浠嶇劧鑷敱鑷垜 姘歌繙楂樺敱鎴戞瓕
[03:15.16]璧伴亶鍗冮噷
[03:19.41]
[03:19.99]鍘熻皡鎴戣繖涓?鐢熶笉缇佹斁绾电埍鑷敱
[03:26.78]涔熶細鎬曟湁涓?澶╀細璺屽??
[03:33.05]鑳屽純浜嗙悊鎯? 璋佷汉閮藉彲浠?
[03:38.88]鍝細鎬曟湁涓?澶╁彧浣犲叡鎴?
[03:45.72]鑳屽純浜嗙悊鎯? 璋佷汉閮藉彲浠?
[03:51.71]鍝細鎬曟湁涓?澶╁彧浣犲叡鎴?
[03:57.38]
[03:57.88]鍘熻皡鎴戣繖涓?鐢熶笉缇佹斁绾电埍鑷敱
[04:04.23]涔熶細鎬曟湁涓?澶╀細璺屽??
[04:10.52]鑳屽純浜嗙悊鎯? 璋佷汉閮藉彲浠?
[04:16.63]鍝細鎬曟湁涓?澶╁彧浣犲叡鎴?
[04:22.80]lojgajgiagjioajgiogjoiajgaigjioagj
g

可以看到只用了InputStream,FileInputStream俩个类,输出结果中文是乱码,因为文件本身是UTF_8格式的,默认用了GBK,

下面改进


InputStreamReader构造函数

可以看到它的构造函数可以指定字符集

private void readLrc() {
        //F盘根目录下有一个海阔天空.lrc文件,注意这里的转义符
        File file = new File("F:\\海阔天空.lrc");
        InputStream in = null;
        
        try {
            in = new FileInputStream(file);
            
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");//修改字符集
            BufferedReader bu = new BufferedReader(reader);//使用buffer缓冲
            
            int position ;//读取位置
            while((position = bu.read()) != -1){
                System.out.println(bu.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

输出

02:15.26]也会怕有一天会跌倒
02:21.41]背弃了理想 谁人都可以
02:27.56]哪会怕有一天只你共我
02:33.38]
03:08.48]仍然自由自我 永远高唱我歌
03:15.16]走遍千里
03:19.41]
03:19.99]原谅我这一生不羁放纵爱自由
03:26.78]也会怕有一天会跌倒
03:33.05]背弃了理想 谁人都可以
03:38.88]哪会怕有一天只你共我
03:45.72]背弃了理想 谁人都可以
03:51.71]哪会怕有一天只你共我
03:57.38]
03:57.88]原谅我这一生不羁放纵爱自由
04:04.23]也会怕有一天会跌倒
04:10.52]背弃了理想 谁人都可以
04:16.63]哪会怕有一天只你共我
04:22.80]lojgajgiagjioajgiogjoiajgaigjioagj
一个大神的理解

超链接

  1. 首先获得一个文件句柄。File file = new File(); file即为文件句柄。两人之间连通电话网络了。接下来可以开始打电话了。

  2. 通过这条线路读取甲方的信息:new FileInputStream(file) 目前这个信息已经读进来内存当中了。接下来需要解读成乙方可以理解的东西

  3. 既然你使用了FileInputStream()。那么对应的需要使用InputStreamReader()这个方法进行解读刚才装进来内存当中的数据

  4. 解读完成后要输出呀。那当然要转换成IO可以识别的数据呀。那就需要调用字节码读取的方法BufferedReader()。同时使用bufferedReader()的readline()方法读取txt文件中的每一行数据哈。


读取文件方法大全

  1. 按字节读物文件内容
  2. 按字符读取文件内容
  3. 按行读取文件内容
  4. 随机读取文件内容

代码转载
[Java]读取文件方法大全

这个已经很详细

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

复制文件(输出流)

private void readLrc() {
        //F盘根目录下有一个海阔天空.lrc文件,注意这里的转义符
        File file = new File("F:\\海阔天空.lrc");
        File outFile = new File("F:\\海阔天空OUT.lrc");
        InputStream in = null;
        OutputStream os = null;
        try {
            in = new FileInputStream(file);
            os = new FileOutputStream(outFile);
            
            int position;
            
            while ((position = in.read()) != -1) {
                os.write(position);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

只要相应的在读取文件的时候用输出流写入文件即可


高效的RandomAccessFile

这是对RandomAccessFile速度改进

高效的RandomAccessFile

高效的RandomAccessFile【续】


注意

1 RandomAccessFile 的readLine()会丢失首字符

解决方法,

while ((position = randomFile.read()) != -1) {
            }

这里的

randomFile.read()

每次都会先读取一个字节出来,所以后面的

randomFile.readLine()

读取的就是每行少一个字节
应该

while ((position = randomFile.readline()) != -1) {
            }

2 RandomAccessFile中文乱码

系统默认格式是"ISO-8859-1",输出时候要转码

System.out.println(new String(randomFile.readLine().getBytes("ISO-8859-1"), "UTF-8"));

更多

Java IO流操作汇总: inputStream 和 outputStream

相关文章

  • JAVA IO流读写操作

    目录 读涉及到的API 创建一个最普通的读文件操作 读取文件方法大全 复制文件(输出流) 高效的RandomAcc...

  • Java 学习笔记(14)—— 文件操作

    java文件操作主要封装在Java.io.File中,而文件读写一般采用的是流的方式,Java流封装在 java....

  • JAVA IO基础知识

    JAVA IO流采用的是装饰器设计模式,通过IO操作可以完成对特定设备进行数据的读写操作,深入理解IO的设计和使用...

  • java中的IO

    Java中的IO IO流也是种对象,Java中的一切都是对象。 IO操作的目标:从数据源中读取数据,以及将数据读写...

  • java使用io缓冲流

    首先明确java中的io流就是 input/output 在使用中有writer和read读写操作, 在使用中的步...

  • Java常用包的主要作用

    java.io io流相关操作java.nio 新io操作java.lang 核心功能包,线程,System,基本...

  • 【JavaSE(十三)】JavaIO流(中)

    1 IO流 1.1 IO流概述 Java中使用 IO流 来读取和写入,读写设备上的数据、硬盘文件、内存、键盘等等,...

  • 从源码设计角度理解Java IO

    概述 Java的核心库java.io提供了全面的IO接口。包括:文件读写、标准设备输出等。Java中IO是以流为基...

  • java笔记--IO流(字符流和字节流)

    IO流: 用来处理设备之间的数据传书。Java对数据的操作是通过流的方式。Java用于操作流的对象都在IO包中。流...

  • java32(IO输入与输出--01概述)

    IO流: IO流用来处理设备之间的数据传输。 java对数据的操作是通过流的方式。 java用于操作流的对...

网友评论

      本文标题:JAVA IO流读写操作

      本文链接:https://www.haomeiwen.com/subject/gyebottx.html