1-11 java常用的文件读写操作

FileInputStream、FileOutputStream和FileReader、FileWriter用法

回到第一章:目录



前言

按读写方法,对文件的读写操作方法有以下几种类型:
1、以字节方式读写,适合所有文件类型;
2、以字符方式单个或按行读写,适合文本文件。


这里仅介绍使用2种常用的文件读写方法:字节方式读写和按行读写:FileInputStream、FileOutputStream和FileReader、FileWriter用法

一、FileInputStream和FileOutputStream用法

1、新建工程:FileOperation
在这里插入图片描述

2、新建包:
在这里插入图片描述

3、创建文件读写的工具类:FileOperation
代码如下:

package com.my.file;

import java.io.*;

/**
 * 文件读写操作类
 */
public class FileOperation {
    /**
     * 根据输入的文件路径读取文件内容,仅支持读取文本文件。
     * @param filePath
     * @return
     */
    public static String readFromFile(String filePath){
        //输入检查:如果输入的文件不存在则返回空字符串
        File file = new File(filePath);
        if (!file.isFile()){
            return "";
        }
        //开始读取文件
        String result = "";
        //读文件的缓存
        byte[] temp = new byte[1024];
        try {
            FileInputStream fis = new FileInputStream(file);
            // 使用 循环读取, FileInputStream的read方法,会一次读取内容放到temp。
            // 读取内容的多少根据temp定义的大小而定。如果没有数据可读了,read方法会返回-1.
            while(fis.read(temp) != -1){
                result = result + new String(temp);
            }
            fis.close();
        } catch (FileNotFoundException e) {
            System.out.println(filePath + " 文件没有找到。");
            return "";
        } catch (IOException e) {
            System.out.println(filePath + " 读文件时发生异常。");
            return "";
        }
        return result;
    }

    /**
     * 将字节数组的内容写入文件
     * @param filePath
     * @param bytes
     * @return
     */
    public static boolean writeToFile(String filePath, byte[] bytes){
        File file = new File(filePath);
        if (!file.exists()){ //文件若不存在则创建一个
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            out.write(bytes);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            System.out.println(filePath + " 文件没有找到。");
            return false;
        } catch (IOException e) {
            System.out.println(filePath + " 写文件时发生异常。");
            return false;
        }
        return  true;
    }

    /**
     *  使用FileReader读文本文件
     * @param filePath
     * @return
     */
    public static String readFileByLine(String filePath){
    //输入检查:如果输入的文件不存在则返回空字符串
    File file = new File(filePath);
    if (!file.isFile()){
        return "";
    }
    //开始读取文件
    String result = "";
    String temp = "";
    try {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        while ((temp = br.readLine()) != null){
            result = result + br;
        }
        br.close();
        fr.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}
    /**
     * 将字符串内容写入文件,使用FileWriter
     * @param filePath
     * @param bytes
     * @return
     */
    public static boolean writeToFileByFileWriter(String filePath,String content){
        File file = new File(filePath);
        if (!file.exists()){ //文件若不存在则创建一个
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            fw.close();
        } catch (FileNotFoundException e) {
            System.out.println(filePath + " 文件没有找到。");
            return false;
        } catch (IOException e) {
            System.out.println(filePath + " 写文件时发生异常。");
            return false;
        }
        return  true;
    }
}
在这个位置新建一个文件:E:\new\1.11\names.txt 内容为:

张三,男,19岁
李四,男,20岁

4、创建测试类(main函数入口类):FileOperationTest
代码如下:

package com.my.file;

public class FileOperationTest {
    public static void main(String[] args) {
        //1、按字节方式读取
        //从文件读取内容并打印
        String filePath="E:\\new\\1.11\\names.txt";
        String content = FileOperation.readFromFile(filePath);
        System.out.println(filePath+"文件里的内容为:\n"+content);


        //将读取的文件内容,增加数据并写入另一个文件
        content = content.trim();//去掉字符串首尾的空格
        content = content + "\n" + "王九,男,22岁";
        FileOperation.writeToFile("E:\\new\\1.11\\names_add.txt",content.getBytes());
        //检查E:\new\1.11\names_add.txt的内容,应该为:
        //张三,男,19岁
        //李四,男,20岁
        //王九,男,22岁

        //2、按字符方式,按行读取
        //从文件读取内容并打印
        filePath="E:\\new\\1.11\\names.txt";
        content = FileOperation.readFileByLine(filePath);
        content = content.trim();
        System.out.println(filePath+"文件里的内容为:\n"+content);

        content = content + "\n" + "赵九,男,32岁";
        FileOperation.writeToFileByFileWriter("E:\\new\\1.11\\names_add2.txt",content);

    }
}


<font color=#999AAA >5、运行查看结果:

在这里插入图片描述
在这里插入图片描述

/** * 一、BufferedReader类 public class BufferedReader extends Reader * 从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。 可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值足够大。 * 通常,Reader 所作的每个读取请求都会导致对底层字符或字节流进行相应的读取请求。因此,建议用 BufferedReader包装所有其 read() * 操作可能开销很高的 Reader(如 FileReader和 InputStreamReader)。 * BufferedReader流能够读取文本行,通过向BufferedReader传递一个Reader对象 * ,来创建一个BufferedReader对象,之所以这样做是因为FileReader没有提供读取文本行的功能. * * 二、InputStreamReader类 * * InputStreamReader 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。 * * 构造方法: * * InputStreamReader isr = new InputStreamReader(InputStream * in);//构造一个默认编码集的InputStreamReader类 * * InputStreamReader isr = new InputStreamReader(InputStream in,String * charsetName);//构造一个指定编码集的InputStreamReader类。 * * 参数 in对象通过 InputStream in = System.in;获得。//读取键盘上的数据。 * * 或者 InputStream in = new FileInputStream(String fileName);//读取文件中的数据。可以看出 * FileInputStream 为InputStream的子类。 * * 主要方法:int read();//读取单个字符。 int read(char []cbuf);//将读取到的字符存到数组中。返回读取的字符数。 * * 三、FileWriter(少量文字) 和 BufferedWriter(大量文字)实现简单文件写操作 * @author hulk */
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值