使用FileRead,BufferedReader,FileWriter,BufferedWriter的文件读写功能改写查看,创建和删除文件或目录
时间: 2024-03-19 12:46:32 浏览: 61
好的,我会尝试回答你的问题。以下是使用Java中的File、FileReader、BufferedReader、FileWriter和BufferedWriter类来实现文件读写和文件/目录的创建、查看和删除的示例代码:
1. 查看文件/目录
```java
import java.io.File;
public class FileViewer {
public static void main(String[] args) {
String path = "C:\\Users\\User\\Documents";
File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
System.out.println("目录 " + path + " 包含以下文件/目录:");
String[] files = file.list();
for (String f : files) {
System.out.println(f);
}
} else {
System.out.println("文件 " + path + " 存在.");
}
} else {
System.out.println("文件/目录 " + path + " 不存在.");
}
}
}
```
2. 创建目录
```java
import java.io.File;
public class DirectoryCreator {
public static void main(String[] args) {
String path = "C:\\Users\\User\\Documents\\test";
File dir = new File(path);
if (dir.mkdir()) {
System.out.println("目录 " + path + " 创建成功.");
} else {
System.out.println("目录 " + path + " 创建失败.");
}
}
}
```
3. 创建文件并写入内容
```java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) {
String fileName = "C:\\Users\\User\\Documents\\test\\test.txt";
String content = "Hello, world!";
File file = new File(fileName);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(content);
System.out.println("文件 " + fileName + " 写入成功.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
4. 读取文件内容
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderDemo {
public static void main(String[] args) {
String fileName = "C:\\Users\\User\\Documents\\test\\test.txt";
File file = new File(fileName);
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
5. 删除文件/目录
```java
import java.io.File;
public class FileDeleter {
public static void main(String[] args) {
String path = "C:\\Users\\User\\Documents\\test\\test.txt";
File file = new File(path);
if (file.delete()) {
System.out.println("文件 " + path + " 删除成功.");
} else {
System.out.println("文件 " + path + " 删除失败.");
}
path = "C:\\Users\\User\\Documents\\test";
file = new File(path);
if (file.delete()) {
System.out.println("目录 " + path + " 删除成功.");
} else {
System.out.println("目录 " + path + " 删除失败.");
}
}
}
```
希望以上示例代码能够帮助你解决问题。
阅读全文