栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java文件读写操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java文件读写操作

FileWriter和FileReader

对文件内容按字符读取

public class WriteRead1 {
    public static void main(String[] args) throws IOException {
        write1();
        read1();
    }

    private static void read1() throws IOException {
        File file = new File("c:/temp/a.txt");
        FileReader fr = new FileReader(file);
        char[] ch = new char[100];
        fr.read(ch);
        for (char c:ch){
            System.out.println(c);
        }
    }

    private static void write1() throws IOException {
        File file = new File("c:/temp/a.txt");
        //如果文件不存在则进行新建文件
        if (!file.exists()){
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file);
        fw.write("Hello world");
        fw.flush();
        fw.close();
    }

}
BuffredReader和BufferedWriter

对文件内容进行整行读取

public class WriteRead2 {
    public static void main(String[] args) throws IOException {
        write2();
        read2();
    }

    private static void read2() throws IOException {
        File file = new File("c:/temp/a.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while((line = br.readLine()) != null){
            System.out.println(line);
        }
        br.close();
    }

    private static void write2() throws IOException {
        File file = new File("c:/temp/a.txt");
        //如果文件不存在则新建文件
        if (!file.exists()){
            file.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write("Hello world");
        bw.newline();
        bw.flush();
        bw.close();
    }
}
FileInputStream和FileOutputStream

以字节的形式写入文件,读取文件时先读取字节数组,再将字节数组转换为字符串形式

public class WriteRead3 {
    public static void main(String[] args) throws IOException {
        write3();
        read3();
    }

    private static void read3() throws IOException {
        File file = new File("c:/temp/a.txt");
        FileInputStream fis = new FileInputStream(file);
        byte[] bys = new byte[100];
        while (fis.read(bys, 0, bys.length) != -1) {
            System.out.println(new String(bys));
        }
        fis.close();
    }

    private static void write3() throws IOException {
        File file = new File("c:/temp/a.txt");
        //如果文件不存在则新建文件
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write("Hello world".getBytes());
        fos.close();
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/318293.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号