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

介绍Java中常用的文件操作函数

发布时间:2023-06-27 06:06:56

Java是一种面向对象的编程语言,广泛应用于开发Web应用程序、桌面应用程序和移动应用程序。在这篇文章中,我们将介绍Java中常用的文件操作函数。

1. 创建文件

Java中创建文件的函数是File类中的createNewFile()方法。这个方法用于在指定位置创建一个新的文件。

例如:

File file = new File("D:\\test\\example.txt");
file.createNewFile();

上面的代码将在D盘的test文件夹中创建一个名为example.txt的文件。

2. 写入文件

Java中写入文件的函数有多种实现方式,其中比较常用的是使用FileWriter类。

例如:

FileWriter writer = new FileWriter("D:\\test\\example.txt");
writer.write("Hello World!");
writer.close();

上面的代码将在example.txt文件中写入字符串"Hello World!",并在完成后关闭writer对象。

3. 读取文件

Java中读取文件的函数也有多种实现方式,其中比较常用的是使用FileReader类。

例如:

FileReader reader = new FileReader("D:\\test\\example.txt");
int data = reader.read();
while(data != -1) {
    System.out.print((char) data);
    data = reader.read();
}
reader.close();

上面的代码将读取example.txt文件中的每一个字符,直到读取完整个文件。

4. 复制文件

Java中复制文件的函数是使用FileInputStream类和FileOutputStream类。

例如:

FileInputStream in = new FileInputStream("D:\\test\\input.txt");
FileOutputStream out = new FileOutputStream("D:\\test\\output.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
    out.write(buffer, 0, bytesRead);
}
in.close();
out.close();

上面的代码将input.txt文件中的内容复制到output.txt文件中。

5. 删除文件

Java中删除文件的函数是使用File类中的delete()方法。

例如:

File file = new File("D:\\test\\example.txt");
if(file.delete()) {
    System.out.println(file.getName() + " is deleted!");
} else {
    System.out.println("Delete operation is failed.");
}

上面的代码将删除example.txt文件,并输出成功或失败信息。

总结

上述五个文件操作函数是Java中常用的文件操作函数,可以用于创建、写入、读取、复制和删除文件。这些函数都有其特定的实现方式和使用场景,开发者可以根据自己的需要选择适合的函数进行文件操作。