读取File:String index超出范围时:-1

时间:2016-02-10 05:41:12

标签: java

我是java开发的新手,请你帮我找到以下错误的解决方案。我的要求是:如果我给我的DirectoryName,它必须从Directory读取所有文件,它必须打印每个文件扩展名,文件名,路径名。注意:DirectoryName包含子目录,在子目录中还有一个目录,然后它包含该文件。 所以当我运行代码时,我得到的错误是: d:\ Testfolder \ FileUtilities.java

  

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:   字符串索引超出范围:-1

public class FolderSearch {
public void listFilesAndFilesSubDirectories(String DirectoryName)
{
    File file = new File(DirectoryName);
    File[] filelist = file.listFiles();
    for(File pathname:filelist)
    {
    if(pathname.isFile())
        {
            String FPATH = pathname.getAbsolutePath();
            System.out.println(FPATH);
            Filename myfilename = new Filename(FPATH, '/', '.');

            System.out.println("Path =" + myfilename.fpath());
            System.out.println("FileName =" + myfilename.fname());
            System.out.println("Ext =" + myfilename.extension());   
        }
        else if(pathname.isDirectory())
        {
            listFilesAndFilesSubDirectories(pathname.getAbsolutePath());
        }
    } ``
}
public static void main (String [] args)
{
    FolderSearch fs = new FolderSearch();
    final String DirectoryName = "D:/Testfolder";
    fs.listFilesAndFilesSubDirectories(DirectoryName);
}
}

public class Filename {
protected String filepath;
protected char pathseparator;
protected char extension;
Filename(String str,char ps,char e)
{
    filepath = str;
    pathseparator = ps;
    extension = e;
}
public String extension()
{
    int dot = filepath.lastIndexOf(extension);
    return filepath.substring(dot + 1);
}
public String fname()
{
    int dot = filepath.lastIndexOf(extension);
    int sep = filepath.lastIndexOf(pathseparator);
    return filepath.substring(sep + 1, dot);
}
public String fpath()
{
    int sep = filepath.lastIndexOf(pathseparator);
    return filepath.substring(0, sep);
}
}

2 个答案:

答案 0 :(得分:1)

在您的代码中,您必须检查以确保lastIndexOf没有返回-1

例如

public String extension()
{
    int dot = filepath.lastIndexOf(extension);
    // if extension is not found then -1 is returned
    if (dot == -1) {
        return null;  // maybe throw a an exception
    }
    return filepath.substring(dot + 1);
}

答案 1 :(得分:0)

我知道,为什么它返回-1。因为输出文件有一个反斜杠分隔符' \'但是我正在通过' /'作为角色。 所以我通过传递' \'双反斜杠作为我在FileName类中的路径分隔符的参数。 这是我传递的文件:

C:\Users\sl00338409\Desktop\WorkSpace\javainterface\javainterface\projects\taskinterface\datasource\ClarityTaskDataSource.java

所以我需要在构造函数中将反斜杠作为字符传递,而不是传递斜杠' /'。我通过传递' \\'得到了输出。作为构造函数中的字符参数。