Soufiane Kharroubi
Soufiane Kharroubi

Reputation: 19

get path of a file in java

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 :)

Upvotes: 1

Views: 4589

Answers (5)

Tom
Tom

Reputation: 17597

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

Upvotes: 0

user2708647
user2708647

Reputation: 436

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

Upvotes: 0

DrDoofenshmirtz
DrDoofenshmirtz

Reputation: 1

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?

Upvotes: 0

Amit
Amit

Reputation: 411

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

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

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();
}

Upvotes: 1

Related Questions