get path of a file in java

2019-08-11 11:17发布

My problem is very simple and yet I can't figure out how to solve it. I have text files in a folder: "C:/aaa/bbb/ccc/ddd/test.txt" And excel files in a folder within the text files folder: "C:/aaa/bbb/ccc/ddd/excelFiles/test.xls" Both text and excel files have the same name.

I would like to be able to access the path of those excel files. What I did is: this.file.getParent()+"\\"+"excelFiles"+"\\"+file.getName().substring(0, fileName.indexOf('.'))+".xls"

I get a "String index out of range" error. Thank you for your help :)

5条回答
Bombasti
2楼-- · 2019-08-11 11:41

You might want to try this ->

String dynamicExcelFileName = file.getName().substring(0, fileName.indexOf('.'))

into a variable and use it in the path for accessing the excel file.

this way you get to be extra sure to check if the path is properly captured in variable or not and thus less chances of getting index out of range error.

plus the code is more readable

查看更多
何必那么认真
3楼-- · 2019-08-11 11:48

If I understand your question, one option is to use File.getCanonicalPath() like,

try {
    File f = new File("C:/aaa/bbb/ccc/ddd/excelFiles/test.xls");
    System.out.println(f.getCanonicalPath());
} catch (IOException e) {
    e.printStackTrace();
}
查看更多
Bombasti
4楼-- · 2019-08-11 11:48

This could be achieved quite easily, even without using existing libraries like FileUtils.

These three method can create the corresponding Excel File object for your text object

private File getExcelFile(final File txtFile) throws IOException {
    final String path = txtFile.getCanonicalPath();
    final String directory = path.substring(0, path.lastIndexOf(System.getProperty("file.separator")));
    return new File(getExcelSubdirectory(directory), getExcelFilename(txtFile.getName()));
}

private File getExcelSubdirectory(final String parent) {
    return new File(parent, "excelFiles");
}

private static String getExcelFilename(final String filename) {
    return filename.substring(0, filename.lastIndexOf('.')) + ".xls";
}

If you use them like this:

File txt = new File("C:/aaa/bbb/ccc/ddd/test.txt");
System.out.println(txt.getCanonicalPath());
File excel = getExcelFile(txt);
System.out.println(excel.getCanonicalPath());

.. it will print:

C:\aaa\bbb\ccc\ddd\test.txt
C:\aaa\bbb\ccc\ddd\excelFiles\test.xls
查看更多
看我几分像从前
5楼-- · 2019-08-11 11:57

this.file.getParent()+"\"+"excelFiles"+"\"+file.getName().substring(0, this.file.getName().indexOf('.'))+".xls"

查看更多
SAY GOODBYE
6楼-- · 2019-08-11 11:59

Looking at your snippet, I can see that you're accessing the file's name in two different ways:

file.getName().substring(...)

and

fileName.indexOf(...).

Are you sure that fileName is not empty when you try to determine the index of the dot?

查看更多
登录 后发表回答