我正在制作一个程序,我将从 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/