使用Java进行文件操作:读写、复制、删除
在Java中,我们可以使用java.io
包中的类来处理文件操作。以下是几种常见操作的示例:
- 读写文件:
```java
import java.io.*;
// 写入文件
public void writeToFile(String content, String fileName) throws IOException {
File file = new File(fileName);
// 如果文件不存在,创建它
if (!file.exists()) {
file.createNewFile();
}
// 使用Writer写入内容到文件中
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.close();
}
// 读取文件
public String readFromFile(String fileName) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new FileNotFoundException(“File does not exist: “ + fileName);
}
// 使用BufferedReader读取内容到字符串中
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder contentBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
contentBuilder.append(line).append(“\n”);
}
reader.close();
return contentBuilder.toString();
}
2. **复制文件**:
```java
import java.io.*;
public void copyFile(String source, String destination) throws IOException {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
byte[] buffer = new byte[1024]; // 指定缓冲区大小
while (fis.read(buffer) != -1) { // 读取源文件
fos.write(buffer); // 写入目标文件
}
fis.close();
fos.close();
}
- 删除文件:
```java
import java.io.*;
public void deleteFile(String fileName) throws IOException {
File file = new File(fileName);
if (file.exists()) { // 文件存在,删除它
file.delete(); // 使用delete()方法删除文件
} else { // 文件不存在,不做处理
System.out.println(“File not found: “ + fileName);
}
}
```
以上就是使用Java进行文件操作的一些基本示例。根据实际需求,你可能需要使用更复杂的API或者类。
还没有评论,来说两句吧...