Java学习笔记2——文件输入输出

本文介绍了一种使用Java实现高效文件读取的方法,通过自定义getint()函数从文本文件中逐个字符读取整数,并利用BufferedReader提高读取效率。此外,还对比了FileInputStream/FileOutputStream与FileReader/FileWriter的使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BufferedRead + FileReader

开了一个BufferedReader,只能按字节读,所以自己写了个getint()
看很多人用了readLine() + str.split(" ") + Integer.parseInt()感觉不如手写方便。
读文件还要throw exception。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Test {
    static int len;
    static int[] a = new int[10000];
    private static BufferedReader br;

    public static int getint() throws IOException {
        int x = br.read();
        while (x < '0' || x > '9') x = br.read();
        int ret = 0;
        while (x >= '0' && x <= '9') {
            ret = ret * 10 + (x - 48);
            x = br.read();
        }
        return ret;
    }

    public static void init() throws IOException {
        br = new BufferedReader(new FileReader("resource/in.txt"));

        len = getint();
        for (int i = 1; i <= len; i++) {
            a[i] = getint();
        }
    }

    public static void print() {
        for (int i = 1; i <= len; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println("");
    }


    public static void main(String[] args) throws IOException {
        init();
        print();
    }
}

FileInputStream & FileOutputStream

这个是流输入输出,本来想用的,直到我发现 FileReaderFileWriter 就是包装过后的FileInputStreamFileOutputStream。所以被我抛弃了。

FileReader & FileWriter

FileWrtier()终于不用按byte输出了,还是这一对input和output用起来舒服。读入其实直接读byte就好了,不用套个buffer。
文件输出需要close,不然就掉了。

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
    static int len;
    static int[] a = new int[10000];
    private static FileReader fin;
    private static FileWriter fout;

    public static int getint() throws IOException {
        int x = fin.read();
        while (x < '0' || x > '9') x = fin.read();
        int ret = 0;
        while (x >= '0' && x <= '9') {
            ret = ret * 10 + (x - 48);
            x = fin.read();
        }
        return ret;
    }

    public static void init() throws IOException {
        fin = new FileReader("resource/in.txt");

        len = getint();
        for (int i = 1; i <= len; i++) {
            a[i] = getint();
        }
    }

    public static void print() throws IOException {
        fout = new FileWriter("resource/out.txt");
        for (int i = 1; i <= len; i++) {
            fout.write(a[i] + " ");
        }
        fout.close();
    }


    public static void main(String[] args) throws IOException {
        init();
        print();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值