Java文件处理函数:文件读写和操作函数汇总
发布时间:2023-06-23 09:53:42
在Java中,文件的读、写和操作是很常见的操作。本文将汇总一些常见的文件处理函数,包括文件读写、文件重命名、文件复制、文件删除等,帮助Java开发者轻松处理文件操作。
一、文件读写函数
1. FileInputStream类
用于打开一个文件输入流,从文件中读取字节流。例如:
FileInputStream fis = new FileInputStream(filePath);
构造函数中的参数filePath是文件路径,需要根据实际情况填写。
2. FileOutputStream类
用于打开一个文件输出流,将字节流写入文件中。例如:
FileOutputStream fos = new FileOutputStream(filePath);
构造函数中的参数filePath是文件路径,需要根据实际情况填写。
3. FileReader类
用于打开一个文件读取流,从文件中读取字符流。例如:
FileReader fr = new FileReader(filePath);
构造函数中的参数filePath是文件路径,需要根据实际情况填写。
4. FileWriter类
用于打开一个文件写入流,将字符流写入文件中。例如:
FileWriter fw = new FileWriter(filePath);
构造函数中的参数filePath是文件路径,需要根据实际情况填写。
二、文件重命名函数
在Java中,文件重命名可以使用File对象的renameTo()方法实现。例如:
File oldFile = new File("oldFileName.txt");
File newFile = new File("newFileName.txt");
oldFile.renameTo(newFile);
注意:在使用renameTo()方法时,需要保证新的文件名没有被占用,否则会抛出IOException异常。
三、文件复制函数
1. 以字节流方式复制文件
可以使用FileInputStream和FileOutputStream类来实现。例如:
public static void copyFile(String sourcePath, String targetPath) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sourcePath);
fos = new FileOutputStream(targetPath);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
}
}
2. 以字符流方式复制文件
可以使用FileReader和FileWriter类来实现。例如:
public static void copyFile(String sourcePath, String targetPath) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(sourcePath);
fw = new FileWriter(targetPath);
char[] buffer = new char[1024];
int length;
while ((length = fr.read(buffer)) > 0) {
fw.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
fr.close();
}
if (fw != null) {
fw.close();
}
}
}
四、文件删除函数
可以使用File对象的delete()方法来删除文件。例如:
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
以上就是文件读写和操作函数的汇总,希望能对Java开发者有所帮助。
