getCanonicalFile与getAbsoluteFile区别
时间: 2024-06-05 09:09:42 浏览: 11
在Java中,File类中有两个方法可以用于获取文件的规范路径和绝对路径,它们分别是getCanonicalFile和getAbsoluteFile。
getCanonicalFile()方法返回的是文件的规范路径,这个路径是相对路径或绝对路径的压缩形式,也就是没有“.”或“..”的路径。如果路径中有符号链接,那么会将符号链接解析为实际的文件路径。
getAbsoluteFile()方法返回的是文件的绝对路径,这个路径是以根目录开始的完整路径,包括所有的父目录。
所以,它们的区别在于getCanonicalFile()方法返回的是文件的规范路径,而getAbsoluteFile()方法返回的是文件的绝对路径。getCanonicalFile()方法会解析路径中的符号链接,而getAbsoluteFile()方法则不会。
相关问题
getcanonicalfile
getCanonicalFile() 是 Java 中 File 类的一个方法,它可以返回一个规范路径的 File 对象。规范路径指的是一个不包含任何相对路径符号("." 或 "..")的绝对路径或相对路径。
例如,假设存在一个文件 /home/user/test.txt,那么以下代码:
```
File file = new File("/home/user/./test.txt");
File canonicalFile = file.getCanonicalFile();
```
将返回一个 File 对象,它的路径是 /home/user/test.txt,因为它已经去除了 "." 相对路径符号。
java 江inputstream转成File对象
可以通过以下步骤将 InputStream 转换为 File 对象:
1. 创建一个临时文件,可以使用 File 类的 createTempFile() 方法。
2. 使用 FileOutputStream 将 InputStream 写入临时文件。
3. 将临时文件转换为 File 对象,可以使用 File 类的 getAbsoluteFile() 或 getCanonicalFile() 方法。
下面是代码示例:
```
import java.io.*;
public class InputStreamToFileExample {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("input.txt");
// 创建临时文件
File tempFile = File.createTempFile("temp", ".txt");
// 写入临时文件
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
// 将临时文件转换为 File 对象
File file = tempFile.getAbsoluteFile();
System.out.println(file.getAbsolutePath());
}
}
```
注意:在使用完临时文件后,需要将其删除。可以使用 File 类的 delete() 方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)