在java中获取文件的路径
我的问题很简单,但我无法弄清楚如何解决它。 我有一个文件夹中的文本文件: “C:/aaa/bbb/ccc/ddd/test.txt” 和excel文件在文本文件夹内的文件夹中: “C:/ aaa/bbb/ccc/ddd/excelFiles/test.xls“ text和excel文件都具有相同的名称。在java中获取文件的路径
我想能够访问这些excel文件的路径。 我做的是: this.file.getParent()+"\\"+"excelFiles"+"\\"+file.getName().substring(0, fileName.indexOf('.'))+".xls"
我得到一个“字符串索引超出范围”的错误。 谢谢您的帮助:)
如果我明白你的问题,一个选择是使用File.getCanonicalPath()
一样,
try {
File f = new File("C:/aaa/bbb/ccc/ddd/excelFiles/test.xls");
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
你可能想试试这个 - >
字符串dynamicExcelFileName =文件。 getName()。substring(0,fileName.indexOf('。'))
写入一个变量并在访问excel文件的路径中使用它。
通过这种方式,您可以确保检查路径是否在变量中正确捕获,从而减少索引超出范围错误的机会。
加上代码更易读
在你的片断来看,我可以看到你在两种不同的方式访问该文件的名称:
file.getName().substring(...)
和
fileName.indexOf(...).
您确定fileName
在您尝试确定点的索引时是否为空?
即使不使用像FileUtils这样的现有库,也可以很容易地实现这一点。
这三种方法可以为你的文本对象
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";
}
创建相应的Excel File
对象。如果你使用它们像这样:
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());
..它会打印:
C:\aaa\bbb\ccc\ddd\test.txt
C:\aaa\bbb\ccc\ddd\excelFiles\test.xls
this.file.getParent()+“\”+“excelFiles”+“\”+ file.getName()。substring(0,this.file.getName ).indexOf('。'))+“.xls”
'fileName'看起来像什么? – fabian 2014-10-17 12:36:25
哦,我刚刚明白我的错误。我把absolutePath放在fileName中。这就是为什么我有一些麻烦!感谢您的帮助球员:) – 2014-10-17 12:50:20