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

介绍Java的I/O函数及实例

发布时间:2023-06-26 10:57:55

Java的I/O函数可以分为字节流和字符流,其中字节流负责将数据一字节一字节地读入内存或从内存写入到文件,而字符流则是负责将数据以字符为单位进行读写。

字节流:

1. FileInputStream:它用于从文件系统中的文件读取字节。如下面的代码:

FileInputStream fis = new FileInputStream("file.txt");

int size = fis.available(); // 获取文件大小

byte[] buffer = new byte[size];

fis.read(buffer); // 读取文件内容

fis.close(); 

2. FileOutputStream:它用于将内容写入到文件中。如下面的代码:

FileOutputStream fos = new FileOutputStream("file.txt");

String str = "Hello, world!";

byte[] buffer = str.getBytes();

fos.write(buffer);

fos.close();

字符流:

1. FileReader:它用于从文件中读取字符。如下面的代码:

FileReader fr = new FileReader("file.txt");

int ch;

while((ch=fr.read())!=-1) {

    System.out.print((char)ch);

}

fr.close();

2. FileWriter:它用于将字符写入到文件中。如下面的代码:

FileWriter fw = new FileWriter("file.txt");

String str = "Hello, world!";

fw.write(str);

fw.close();

除了以上四个函数,还有很多其他的IO函数,它们包括:ByteArrayInputStream、ByteArrayOutputStream、CharArrayReader、CharArrayWriter、DataInputStream、DataOutputStream、ObjectInputStream、ObjectOutputStream、PipedInputStream、PipedOutputStream、PrintStream、PushbackInputStream、RandomAccessFile等等。这些函数提供了不同的读写功能,可以根据需要选择合适的函数进行调用。