gpt4 book ai didi

Java文件对象解释

转载 作者:行者123 更新时间:2023-12-02 10:07:39 25 4
gpt4 key购买 nike

我试图理解为什么 File obj 在下面返回 true。

我的文件“abc.def.txt”位于 Windows 10 中的 C:

File file = new File("\\abc.def.txt");
System.out.println(file != null && file.exists()); // Returns true
File file1 = new File("C:\\abc.def.txt");
System.out.println(file1 != null && file1.exists()); //Returns true

我的 file1 应该返回 true ,因为该位置存在一个名为“abc.def.txt”的文件。

但是我很困惑为什么文件对象返回为 true ,而不是 false 因为在 Windows 中,不会有像\abc.def.txt 这样的位置

请有人帮忙理解一下。

谢谢!

最佳答案

首先,让我们分析一下您的代码正在做什么:

  1. \\abc.def.txt 处创建一个名为 file 的对象
  2. 打印 true 如果 file 对象不为 null file.exists( ) 返回 true
  3. \\abc.def.txt 处创建一个名为 file1 的对象
  4. 打印 true 如果 file1 对象不为 null file.exists( ) 返回 true

为了回答您的问题编辑,在 Windows 中,以 \ 开头假定您将进入“根”级目录。在您的示例中,除非另有说明,否则应为 C:

您正在创建这两个文件,您的真/假检查实际上是查看它们是否存在,而不是它们存在的位置。如果你想检查它们存在的位置,你可以这样做:

File file = new File("\\abc.def.txt");
boolean check = new File(directory, file).exists();
System.out.println(check); // Returns true
File file1 = new File("C:\\abc.def.txt");
boolean check1 = new File("C:\\", "abc.def.txt").exists();
System.out.println(check1); //Returns true

关于Java文件对象解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55227604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com