实用的Java文件处理函数
发布时间:2023-07-05 23:47:43
在Java中,文件处理是一项非常常见且实用的任务。以下是一些实用的Java文件处理函数:
1. 创建文件
你可以使用File类的createNewFile方法来创建一个新的空文件。示例代码如下:
File file = new File("path/to/file.txt");
try {
boolean isCreated = file.createNewFile();
if (isCreated) {
System.out.println("文件创建成功");
} else {
System.out.println("文件已存在");
}
} catch (IOException e) {
e.printStackTrace();
}
2. 读取文件内容
你可以使用Java的BufferedReader类来读取文本文件的内容。示例代码如下:
File file = new File("path/to/file.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
3. 写入文件内容
你可以使用Java的BufferedWriter类来向文本文件中写入内容。示例代码如下:
File file = new File("path/to/file.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
4. 复制文件
你可以使用Java的FileInputStream和FileOutputStream来复制文件。示例代码如下:
File sourceFile = new File("path/to/source.txt");
File destinationFile = new File("path/to/destination.txt");
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
5. 删除文件
你可以使用File类的delete方法来删除文件。示例代码如下:
File file = new File("path/to/file.txt");
boolean isDeleted = file.delete();
if (isDeleted) {
System.out.println("文件删除成功");
} else {
System.out.println("文件删除失败");
}
这些是一些常见且实用的Java文件处理函数。通过利用这些函数,你可以轻松地创建、读取、写入、复制和删除文件。
