2013-05-14 28 views
0

我正在制作一个程序,我将从excel文件中读取数据并将它们存储在mysql数据库中。在这个程序中,用户会给出将要使用的文件的路径。这样做的代码如下。不同类别的错误文件路径java

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中提供这些命令?用户如何理解他输入的内容是错误的?

+1

究竟是什么你的问题? – DeadlyJesus 2013-05-14 14:02:13

+0

没有自动诊断某个文件系统路径无效的确切原因的方法。您必须为您感兴趣的每种特殊情况编写代码。 – 2013-05-14 14:04:52

回答

3

你应该做一个确认循环:

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); 
    } 
} 
+0

谢谢,但是,我将如何指定用户何时给路径编辑错误?例如字符为:/ ,,“这是不可识别的? – dedmar 2013-05-15 08:21:24

+0

循环会继续并要求他提供一个有效的路径。我做了一个编辑来清除它。 – 2013-05-15 08:46:05

+0

是的,但这是一个可能的错误,其中文件不如果用户插入的文件实际存在,但用户没有给出正确的路径,那么这个文件就是C:\\ Users \\ myuser \\ Documents \\ tests.xls,而不是写入C :. \ Users.myuser。\ Documents。\ testing.xls我们如何说给定路径的结构是错误的? – dedmar 2013-05-15 08:52:53