Java基础之IO流

下面我将用代码演示Java中IO流的基本使用方法。
使用FileInputStream读取文件中的字节数据:

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("example.txt");
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出结果是将example.txt文件中的内容输出到控制台上,例如:

Hello, world!
This is an example file.

解释一下以上代码的的意思

我们首先创建了一个FileInputStream对象,并打开了名为example.txt的文件(这里具体写你对应的路径)。然后,我们使用read()方法读取文件中的字节数据,然后再将其转换为字符输出到控制台。最后,我们关闭了输入流对象。这是整个流程。

使用BufferedReader和FileWriter读取和写入文本文件的例子:

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

public class BufferedReaderExample {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("input.txt"));
            FileWriter fw = new FileWriter("output.txt");
            String line;
            while ((line = br.readLine()) != null) {
                fw.write(line);
                fw.write("\n");
            }
            br.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

输出结果是将input.txt文件中的内容逐行写入到output.txt文件中,例如:
input.txt文件内容:

This is the first line.
This is the second line.
This is the third line.

output.txt文件内容:

This is the first line.
This is the second line.
This is the third line.

解释一下以上代码的的意思

在上面的代码中,我们创建了一个BufferedReader对象和一个FileWriter对象,并打开了名为input.txt的文件和名为output.txt的文件。然后,我们使用readLine()方法逐行读取文件中的字符数据,并将其写入到输出文件中。最后,我们关闭了输入流对象和输出流对象。

总结一下:这些例子只是Java中IO流的基本用法,Java的IO流类库还提供了更多的功能和选项,可以根据具体需求进行选择和使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值