如何在 Java 中知道实际文件存储在哪里?


在 Java 中,您可以使用 File 类来表示和操作文件和目录路径。您还可以使用 File 类来创建、删除和操作文件和目录。

要了解实际文件在 Java 中存储在哪里,可以使用 File 类的 getAbsolutePath() 方法。此方法返回文件的绝对路径的字符串表示形式,其中包括从根目录到文件的完整路径。

让我们深入了解本文,看看实际文件在 Java 中保存在哪里。

例如

假设源文件为

" example.txt”

执行获取实际文件存储位置的操作后,结果将为

文件的绝对路径:C:\Users\SAMPLE \Desktop\satya\Program\example.txt

算法

步骤 1:声明并初始化源文件路径。

步骤 2:使用 getAbsolutePath() 方法获取实际文件的位置。

步骤 3: 打印结果。

语法

getAbsolutePath():它是 Java API 中 File 类的一个方法,它将文件或目录的绝对路径作为字符串返回。

多种方法

我们提供了不同的方法来解决这个问题。

1. 使用静态方法

2. 使用用户定义的方法

让我们逐一查看程序及其输出。

方法 1:使用静态方法

在这种方法中,通过传递文件名来初始化 File 类对象。然后根据算法,使用 getAbsolutePath() 方法获取文件在 Java 中存储的绝对路径。

示例

import java.io.File;

public class Main 
{
   //main method
   public static void main(String[] args) 
   {
      File file = new File("example.txt");
	  //getting the location of actual file
      String absolutePath = file.getAbsolutePath();
	  //print the result
      System.out.println("Absolute path of file: " + absolutePath);
   }
}

输出

Absolute path of file: /home/cg/root/64927fe34456a/example.txt

方法 2:使用用户定义的方法

在这种方法中,从 main 方法调用用户定义的方法。在用户定义的方法中,通过传递文件名来初始化 File 类对象。然后根据算法,使用 getAbsolutePath() 方法获取文件在 Java 中存储的绝对路径。

示例

import java.io.File;

public class Main
{
   //main method
   public static void main(String[] args) 
   {
    //calling user defined method
    func();
   }

   //user defined method
   static void func()
   {
	  //getting the file path 
      File file = new File("myfile.txt");

	  //getting the location of actual file
      String absolutePath = file.getAbsolutePath();

	  //print the result
      System.out.println("Absolute path of file: " + absolutePath);
   }
}

输出

Absolute path of file: /home/cg/root/64927fe34456a/myfile.txt

在这篇文章中,我们探讨了如何使用 Java 编程语言来了解实际文件存储在哪里。

更新于: 2023 年 8 月 17 日

92 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.