通过Java函数对文件进行读取和写入操作
Java提供了非常方便的文件读取和写入功能,同时也提供了许多用于操作文件的类。在本文中,我们将详细介绍如何使用Java函数对文件进行读取和写入操作。
一、文件读取
Java中用于读取文件的主要类是InputStream和Reader,其中InputStream是字节流读取,而Reader是字符流读取。InputStream可以读取任何形式的二进制文件,而Reader仅能读取文本文件。
1. 使用InputStream读取文本文件
我们可以使用InputStream读取文本文件中的内容,代码如下:
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try {
InputStream is = new FileInputStream("fileName.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
String text = new String(buffer);
System.out.println(text);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先使用InputStream对象打开文件,然后使用available()方法获取文件的大小,将其保存到byte[]数组中。接着,我们使用read()函数将文件内容读取到缓冲区中,最后将缓冲区中的内容转换成字符串并输出到控制台。最后,我们关闭InputStream对象。
2. 使用Reader读取文本文件
我们可以使用Reader读取文本文件中的内容,代码如下:
import java.io.*;
public class ReadFile2 {
public static void main(String[] args) {
try {
Reader reader = new FileReader("fileName.txt");
char[] buffer = new char[1024];
StringBuilder sb = new StringBuilder();
while (reader.read(buffer) != -1) {
sb.append(buffer);
}
reader.close();
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先使用Reader对象打开文件,然后使用read()函数将文件内容读取到缓冲区中,最后将缓冲区中的内容转换成字符串并输出到控制台。最后,我们关闭Reader对象。
二、文件写入
Java中用于写入文件的主要类是OutputStream和Writer,其中OutputStream是字节流写入,而Writer是字符流写入。
1. 使用OutputStream写入文本文件
我们可以使用OutputStream写入文本文件,代码如下:
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
String data = "Hello, Java!";
try {
OutputStream os = new FileOutputStream("fileName.txt");
os.write(data.getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先定义了一个字符串变量,然后使用OutputStream对象打开文件,使用write()函数将数据写入文件中,最后关闭OutputStream对象。
2. 使用Writer写入文本文件
我们可以使用Writer写入文本文件,代码如下:
import java.io.*;
public class WriteFile2 {
public static void main(String[] args) {
String data = "Hello, Java!";
try {
Writer writer = new FileWriter("fileName.txt");
writer.write(data);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的代码中,我们首先定义了一个字符串变量,然后使用Writer对象打开文件,使用write()函数将数据写入文件中,最后关闭Writer对象。
三、总结
通过上面的介绍,我们可以看到Java提供了非常方便的文件读取和写入功能,同时也提供了许多用于操作文件的类。无论是读取文本文件还是写入文本文件,Java都提供了非常清晰的API,使得我们可以快速地完成需要的操作。
