Java文件读写操作

Java中I/O流对文件的读写有很多种方法,在这里我主要介绍三种方式,供大家参考。

第一种方式:使用FileWriter和FileReader,对文件内容按字符读取,代码如下

String dir = "E:\\soft\\aaa\\a.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists()) 
    file.createNewFile();
//创建FileWriter对象
FileWriter writer = new FileWriter(file);
//向文件中写入内容
writer.write("the first way to write and read");
writer.flush();
writer.close();

//创建FileReader对象,读取文件中的内容
FileReader reader = new FileReader(file);
char[] ch = new char[100];
reader.read(ch);
for(char c:ch) {
    System.out.print(c);
}
System.out.println();
reader.close();

第二种方式:使用包装类BuffredReader和BufferedWriter,对文件内容进行整行读取,代码如下

String dir = "E:\\soft\\aaa\\b.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists()) 
    file.createNewFile();
//创建BufferedWriter对象并向文件写入内容
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//向文件中写入内容
bw.write("the second way to write and read");
bw.flush();
bw.close();
//创建BufferedReader读取文件内容
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line=br.readLine())!=null) {
    System.out.println(line);
}
br.close();

第三种方式:使用FileInputStream和FileOutputStream,这种方法以字节的形式写入文件,读取文件时先读取字节数组,再将字节数组转换为字符串形式,代码如下:

String dir = "E:\\soft\\aaa\\c.txt";
File file = new File(dir);
//如果文件不存在,创建文件
if (!file.exists()) 
    file.createNewFile();
//创建FileOutputStream对象,写入内容
FileOutputStream fos = new FileOutputStream(file);
//向文件中写入内容
fos.write("the third way to write and read".getBytes());
fos.close();
//创建FileInputStream对象,读取文件内容
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();

类中的整体代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileRW {

    //第一种方式:使用FileWriter和FileReader
    public void firstWay() throws IOException {
        String dir = "E:\\soft\\aaa\\a.txt";
        File file = new File(dir);
        //如果文件不存在,创建文件
        if (!file.exists()) 
            file.createNewFile();
        //创建FileWriter对象
        FileWriter writer = new FileWriter(file);
        //向文件中写入内容
        writer.write("the first way to write and read");
        writer.flush();
        writer.close();

        //创建FileReader对象,读取文件中的内容
        FileReader reader = new FileReader(file);
        char[] ch = new char[100];
        reader.read(ch);
        for(char c:ch) {
            System.out.print(c);
        }
        System.out.println();
        reader.close();
    }

    //第二种方式:使用BuffredReader和BufferedWriter
    public void secondWay() throws IOException {
        String dir = "E:\\soft\\aaa\\b.txt";
        File file = new File(dir);
        //如果文件不存在,创建文件
        if (!file.exists()) 
            file.createNewFile();
        //创建BufferedWriter对象并向文件写入内容
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        //向文件中写入内容
        bw.write("the second way to write and read");
        bw.flush();
        bw.close();
        //创建BufferedReader读取文件内容
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line=br.readLine())!=null) {
            System.out.println(line);
        }
        br.close();
    }

    //第三种方式:使用FileInputStream和FileOutputStream
    public void thirdWay() throws IOException {
        String dir = "E:\\soft\\aaa\\c.txt";
        File file = new File(dir);
        //如果文件不存在,创建文件
        if (!file.exists()) 
            file.createNewFile();
        //创建FileOutputStream对象,写入内容
        FileOutputStream fos = new FileOutputStream(file);
        //向文件中写入内容
        fos.write("the third way to write and read".getBytes());
        fos.close();
        //创建FileInputStream对象,读取文件内容
        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();
    }

    public static void main(String[] args) throws IOException {
        FileRW fileRW = new FileRW();
        fileRW.firstWay();
        fileRW.secondWay();
        fileRW.thirdWay();
    }
}

运行结果如下:

the first way to write and read
the second way to write and read
the third way to write and read

希望对大家有帮助,有什么问题欢迎提问

  • 54
    点赞
  • 330
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
Java中,文件读写操作可能会抛出多种异常。为了确保程序的健壮性,我们需要捕获并处理这些异常。以下是一些可能抛出的异常类型: 1. FileNotFoundException:如果指定的文件不存在,将抛出此异常。 2. IOException:如果读取或写入文件时发生错误,将抛出此异常。 3. SecurityException:如果安全管理器禁止访问指定文件,将抛出此异常。 为了捕获这些异常,我们可以使用try-catch块。以下是一个示例代码,展示如何捕获通过读取和写入文件而抛出的所有异常: ```java import java.io.*; public class FileReadWrite { public static void main(String[] args) { try { // 读取文件 File file = new File("input.txt"); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); // 写入文件 FileWriter fw = new FileWriter("output.txt"); BufferedWriter bw = new BufferedWriter(fw); // 逐行读取并写入文件 String line; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } // 关闭文件 br.close(); fr.close(); bw.close(); fw.close(); } catch (FileNotFoundException e) { System.out.println("文件不存在!"); e.printStackTrace(); } catch (IOException e) { System.out.println("读写文件错误!"); e.printStackTrace(); } catch (SecurityException e) { System.out.println("安全管理器禁止访问文件!"); e.printStackTrace(); } } } ``` 在上面的代码中,我们使用try-catch块捕获了FileNotFoundException、IOException和SecurityException异常。如果捕获到异常,程序将打印错误信息并输出异常堆栈跟踪。注意,在finally块中关闭文件流以确保文件资源得到释放。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值