JAVA IO流读写操作

目录

  • 读涉及到的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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 标准输入输出,文件的操作,网络上的数据流,字符串流,对象流,zip文件流等等,java中将输入输出抽象称为流,就好...
    navy_legend阅读 4,048评论 0 0
  • 一、流的概念和作用。 流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输...
    布鲁斯不吐丝阅读 13,427评论 2 95
  • 一、IO流整体结构图 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称...
    慕凌峰阅读 5,092评论 0 12
  • 1.流的分类 (1)输入输出流输入输出是针对程序运行的内存而言的输入流的基类:InputStream,Reader...
    ql2012jz阅读 3,660评论 0 3
  • “今天是个自由的日子,配了副新眼镜。在等待镜片的时间里,有对夫妻陪自己上大一的女儿来配眼镜。女儿像只洁白的鸽子坐在...
    牙牙乐阅读 2,463评论 0 0

友情链接更多精彩内容