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

实现文件IO操作的Java函数

发布时间:2023-06-23 13:33:09

Java中有许多处理文件IO的函数,主要包括以下几类:

1. FileInputStream和FileOutputStream类

这两个类是Java中最基本的文件IO操作类。FileInputStream类可以用来从文件中读取二进制数据,而FileOutputStream类可以用于向文件写入二进制数据。

例子1:读取文件

FileInputStream in = new FileInputStream("file.txt");    
byte[] data = new byte[in.available()];    
in.read(data);    
in.close();    
String content = new String(data);

例子2:写入文件

FileOutputStream out = new FileOutputStream("file.txt");    
out.write("Hello World".getBytes());    
out.close();

2. FileReader和FileWriter类

这两个类可以用于读取和写入文本文件。FileReader类可以读取一个文本文件,并将其转换为字符串,而FileWriter类可以将一个字符串写入到一个文本文件中。

例子1:读取文本文件

FileReader in = new FileReader("file.txt");    
char[] data = new char[1024];    
in.read(data);    
in.close();    
String content = new String(data);

例子2:写入文本文件

FileWriter out = new FileWriter("file.txt");    
out.write("Hello World");    
out.close();

3. BufferedReader和BufferedWriter类

这两个类与FileReader和FileWriter类类似,不同的是它们可以一次读取多个字符或字符串,并将它们缓冲在内存中,这样可以提高读写效率。

例子1:读取文本文件

BufferedReader in = new BufferedReader(new FileReader("file.txt"));    
String content = "";    
String line = in.readLine();    
while (line != null) {    
    content += line;    
    line = in.readLine();    
}    
in.close();

例子2:写入文本文件

BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));    
out.write("Hello World");    
out.close();

4. RandomAccessFile类

这个类可以读取和写入文件中的任意位置,它支持读、写、跳过等操作。

例子1:读取文件

RandomAccessFile file = new RandomAccessFile("file.txt", "r");
file.seek(4);
byte[] data = new byte[16];
file.read(data);
file.close();
String content = new String(data);

例子2:写入文件

RandomAccessFile file = new RandomAccessFile("file.txt", "rw");
file.seek(4);
file.write("Hello World".getBytes());
file.close();

总结:

上述函数仅是Java中文件IO操作的一部分,还有很多其他函数可以实现更加复杂的操作。在使用这些函数时,需要注意文件路径、读写权限和文件关闭等问题,以避免出现错误。