如何检查(字符串)位置是否是 Java 中的有效保存路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6499609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:07:21  来源:igfitidea点击:

How to check whether a (String) location is a valid saving path in Java?

javavalidationfilelocation

提问by Jér?me Verstrynge

I am receiving a string from user which should be used as a location to save content to a file. This string should contain enough information, like a directory + file name.

我从用户那里收到一个字符串,该字符串应该用作将内容保存到文件的位置。此字符串应包含足够的信息,例如目录 + 文件名。

My question is, how can I check whether the provided string is a valid path to save content to a file (at least in theory)?

我的问题是,如何检查提供的字符串是否是将内容保存到文件的有效路径(至少在理论上)?

It does not matter whether directories are created or not, or whether one has proper access to the location itself. I am only interested in checking the structure of the provided string.

无论是否创建目录,或者是否可以正确访问该位置本身都无关紧要。我只对检查提供的字符串的结构感兴趣。

How should I proceed? I was thinking about creating a Fileobject, then extracting its URI. Is there any better way?

我应该如何进行?我正在考虑创建一个File对象,然后提取它的URI. 有没有更好的办法?

回答by RealHowTo

You can use File.getCanonicalPath() to validate according the current OS rules.

您可以使用 File.getCanonicalPath() 根据当前的操作系统规则进行验证。

import java.io.File;
import java.io.IOException;

public class FileUtils {
  public static boolean isFilenameValid(String file) {
    File f = new File(file);
    try {
       f.getCanonicalPath();
       return true;
    }
    catch (IOException e) {
       return false;
    }
  }

  public static void main(String args[]) throws Exception {
    // true
    System.out.println(FileUtils.isFilenameValid("well.txt"));
    System.out.println(FileUtils.isFilenameValid("well well.txt"));
    System.out.println(FileUtils.isFilenameValid(""));

    //false
    System.out.println(FileUtils.isFilenameValid("test.T*T"));
    System.out.println(FileUtils.isFilenameValid("test|.TXT"));
    System.out.println(FileUtils.isFilenameValid("te?st.TXT"));
    System.out.println(FileUtils.isFilenameValid("con.TXT")); // windows
    System.out.println(FileUtils.isFilenameValid("prn.TXT")); // windows
    }
  }

回答by fipple

Have you looked at Apache Commons IO? This library includes various things for handling path information which may help e.g. FilenameUtils.getPath(String filename)which returns the path from a full filename.

你看过Apache Commons IO吗?该库包括用于处理路径信息的各种内容,这可能会有所帮助,例如FilenameUtils.getPath(String filename)从完整文件名返回路径。

回答by Amadan

Easiest: try to save, listen for exceptions.

最简单:尝试保存,监听异常。

The only time I'd do something more complicated would be if the writing was to be deferred, and you want to give the user his feedback now.

我唯一会做一些更复杂的事情是如果写作被推迟,而你想现在就给用户他的反馈。

回答by Jér?me Verstrynge

Here is what I have so far:

这是我到目前为止所拥有的:

private static boolean checkLocation(String toCheck) {

    // If null, we necessarily miss the directory section
    if ( toCheck == null ) {
        System.out.println("Missing directory section");
        return false;
    }

    String retrName = new File(toCheck).toURI().toString();

    // Are we dealing with a directory?
    if ( retrName.charAt(retrName.length()-1) == '/') {
        System.out.println("Missing file name");
        return false;
    }

    return true;

}

This tells me whether I have a proper directory structure and whether I am pointing to a directory rather than a file. I do not need I/O access.

这告诉我我是否有正确的目录结构以及我是否指向目录而不是文件。我不需要 I/O 访问。

I have noticed that if I use the File.createNewFile()method on a location pointing explicitly to a directory (which does not exist yet), Java creates a file with no extension, which is plain wrong. Either it should create a directory or it should throw some kind of error.

我注意到,如果我File.createNewFile()在显式指向目录(尚不存在)的位置上使用该方法,Java 将创建一个没有扩展名的文件,这是完全错误的。它要么应该创建一个目录,要么应该抛出某种错误。

Also, the File constructors tend to add the current directory if none is provided in the argument. It is not documented, but no real harm in my case.

此外,如果参数中没有提供,文件构造函数倾向于添加当前目录。它没有记录,但在我的情况下没有真正的伤害。

If anyone has a better solution, I'll approve it.

如果有人有更好的解决方案,我会批准它。

EDIT

编辑

I have finally combined the above with the input from RealHowTo.

我终于将上述内容与 RealHowTo 的输入结合起来。