有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java文件系统:UNC路径缺少sharename

我无法访问共享文件夹。 下面是一个示例java程序

import java.nio.file.*;

/**
 * Test
 */
public class Test
{
  public static void main(String[] args)
  {
    String strPath = "//WG0202";
    Path path = FileSystems.getDefault().getPath(strPath).getRoot();
    if (path != null)
    {
      System.out.println(path.toFile().exists());
    }
  }
}

让我们假设如下- 计算机名:WG0202

此计算机中共享的文件夹是:TestFolder

所以如果我把路径设为://WG0202/TetFolder

那就好了

但是如果我给出路径://WG0202

然后它失败了,但有以下例外-

Exception in thread "main" java.nio.file.InvalidPathException: UNC path is missing sharename: //WG0202
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:118)
    at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
    at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
    at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)

共 (1) 个答案

  1. # 1 楼答案

    从文件的Official Javadoc

    User interfaces and operating systems use system-dependent pathname strings to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:

    1. An optional system-dependent prefix string, such as a disk-drive specifier, "/"for the UNIX root directory, or "\\\\" for a Microsoft Windows UNC pathname, and

    2. A sequence of zero or more string names.

    The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file. The empty abstract pathname has no prefix and an empty name sequence.