欢迎访问宙启技术站
智能推送

Java中的IO函数:如何读写文件、输入输出流等操作?

发布时间:2023-06-14 16:05:52

Java是一种面向对象的编程语言,它具有非常强大的IO功能,能够读写文件、网络通信等操作。在Java中,IO是由java.io包提供的。本文将介绍如何使用Java中的IO函数。

IO类别

在Java中,IO操作分为两类:字节操作与字符操作。字节操作适用于二进制数据的操作,字符操作适用于文本数据的操作。Java提供了处理字节和字符的各种IO类。以下是一些常用的类:

1. 字节流分类:

Input Stream

Output Stream

2. 字符流分类:

Reader

Writer

以上分类根据读写内容的数据类型不同来划分,用于读写文件可以根据不同的需求选择不同的流。

读写文件

在Java中,读取文件可以通过FileReader、BufferedReader等类来实现。以下是一个示例:

import java.io.*;

public class ReadFile {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            br.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码中,我们打开文件example.txt,然后使用FileReader和BufferedReader类分别打开文件并读取每一行,最后关闭流。

如果需要写文件,可以用FileWriter、BufferedWriter等类来实现。以下是一个示例:

import java.io.*;

public class WriteFile {
    public static void main(String[] args) {
        try {
            String content = "This is the content to write into file";

            File file = new File("example.txt");
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(content);

            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码中,我们打开文件example.txt,然后使用FileWriter和BufferedWriter类来写入文件内容,最后关闭流。

输入输出流

在Java中,输入输出流的实现方式可以基于内存、文件、网络等。以下是一个简单的输入输出流示例:

import java.io.*;

public class IOExample {
    public static void main(String[] args) {
        try {
            FileInputStream in = new FileInputStream("./example.txt");
            FileOutputStream out = new FileOutputStream("./output.txt");

            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }

            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上述代码中,我们打开文件example.txt并使用FileInputStream类读取文件内容,然后使用FileOutputStream类将内容写入到文件output.txt。

在Java中,还有一些其他的IO类可以被用于输入输出流,如ByteArrayInputStream和ByteArrayOutputStream(适用于基于内存的读写操作)、Socket和ServerSocket(适用于网络通信等操作)等。

总结

Java的IO功能非常强大且易于使用,提供了各种输入输出流来处理不同类型的数据,便于读取、写入、复制等操作。了解IO是Java编程的基础,有助于处理文件读写等任务。