java 文件操作函数,Java文件操作大全
时间: 2023-10-10 15:16:03 浏览: 171
Java文件操作涉及到很多方面,包括文件的创建、读写、复制、删除、重命名等等。下面是一些常用的Java文件操作函数:
1. 创建文件或目录
```java
File file = new File("file.txt");
if (!file.exists()) {
file.createNewFile();
}
```
```java
File dir = new File("dir");
if (!dir.exists()) {
dir.mkdir();
}
```
2. 写入文件
```java
FileWriter writer = new FileWriter("file.txt");
writer.write("Hello World!");
writer.close();
```
```java
FileOutputStream outputStream = new FileOutputStream("file.txt");
outputStream.write("Hello World!".getBytes());
outputStream.close();
```
3. 读取文件
```java
FileReader reader = new FileReader("file.txt");
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) > 0) {
System.out.println(new String(buffer, 0, length));
}
reader.close();
```
```java
FileInputStream inputStream = new FileInputStream("file.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
System.out.println(new String(buffer, 0, length));
}
inputStream.close();
```
4. 复制文件
```java
File source = new File("source.txt");
File target = new File("target.txt");
Files.copy(source.toPath(), target.toPath());
```
5. 删除文件或目录
```java
File file = new File("file.txt");
file.delete();
```
```java
File dir = new File("dir");
FileUtils.deleteDirectory(dir);
```
6. 重命名文件或目录
```java
File file = new File("file.txt");
File newFile = new File("new_file.txt");
file.renameTo(newFile);
```
```java
File dir = new File("dir");
File newDir = new File("new_dir");
dir.renameTo(newDir);
```
以上是一些常用的Java文件操作函数,如果需要更多的文件操作函数,可以查看Java官方文档或第三方库。
阅读全文