java - java不同类别的假文件路径

标签 java file path

我正在制作一个程序,我将从 Excel 文件中读取数据并将它们存储在 mysql 数据库中。在此程序中,用户将给出将使用的文件的路径。执行此操作的代码如下。

 String strfullPath = "";
 Scanner scanner = new Scanner(System. in );
 System.out.println("Please enter the fullpath of the file");
 strfullPath = scanner.nextLine();
 String file = strfullPath.substring(strfullPath.lastIndexOf('/') + 1);
 System.out.println(file.substring(0, file.indexOf('.')));
 @SuppressWarnings("unused")
 String filename = strfullPath.substring(strfullPath.lastIndexOf('\\') + 1);
 System.out.println(filename);
 String[] parts = filename.split("\\.");

然后我希望用户在控制台中给出完整路径时可以选择犯错误。例如,如果他写入了文件夹中不存在的文件,或者如果他写入了无法识别的特殊字符,或者例如如果他以不适当的方式写入了路径。我如何在java中给出这些命令?用户如何知道他输入的内容是错误的?

最佳答案

您应该进行验证循环:

while (true)
{
    System.out.println("Please enter the fullpath of the file:");
    strfullPath = scanner.nextLine();
    File f = new File(strfullPath );
    if (f.canRead()) break;
    System.out.println("Error: File does not exist");
}

编辑 此方法检查路径是否有效并尝试更正它:

public static final String correctPath(final String path) {
    try {
        final String returnValue = new File(path).toPath().toAbsolutePath().normalize().toFile().toString();
        System.out.println(returnValue);
        return returnValue;
    } catch (final InvalidPathException e) {
        System.err.println(e.getMessage());
        final int errorIndex = e.getIndex();
        final String newPath = path.substring(0, errorIndex - 1) + path.substring(errorIndex + 1);
        return correctPath(newPath);
    }
}

关于java - java不同类别的假文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545244/

相关文章:

java - 使用 javax.crypto 时出现 ClassCastException

file - 如何在 Clojure 中从文件中读取多个变量?

php - 如何在 PHP 中正确拆分 PATH 变量?

java - 如何在 Web 应用程序中部署 JbossWS CXF

java - 如何在Java中根据鼠标位置向上旋转物体

java - CardLayout 管理器问题/困惑

java - 将 java 中大型 JSON 解析对象暴露给 UI 的有效方法是什么?

java - 在 java 中传入 args[] 或缺少 args

algorithm - 寻找二叉树中的最长路径

android - 如何在activity类中使用自定义类(扩展View类)来绘制路径而不改变android中主布局的其他部分