2011-02-16 92 views
0

我只想将目录设置为我之前写入文件的路径。将目录设置为文件中的路径

因此我使用:

fileChooser.setCurrentDirectory(new File("path.txt")); 

和path.txt给定该路径。但不幸的是,这并没有解决,我想知道为什么:P。 我想我完全搞错了与setCurrentDic ..

+0

setCurrentDirectory接受路径,而不是文件名。所以你的新文件(“path.txt”)只会表示当前工作目录将被设置为**你的当前目录。再次阅读javadoc。 – asgs 2011-02-16 12:36:47

回答

0
JFileChooser chooser = new JFileChooser(); 

try { 
    // Create a File object containing the canonical path of the 
    // desired directory 
    File f = new File(new File(".").getCanonicalPath()); 

    // Set the current directory 
    chooser.setCurrentDirectory(f); 
} catch (IOException e) { 
} 
1

您必须阅读的path.txt内容。西娅最简单的方法就是通过commons-io

String fileContents = IOUtils.toString(new FileInputStream("path.txt")); 
File dir = new File(fileContents); 

您还可以使用FileUtils.readFileToString(..)

+0

啊好吧,我看到...但IOUtils.toString(新文件(“path.txt”));抛出错误,那toString不适用于参数文件 – NeoGeo 2011-02-16 12:43:38

+0

@NeoGeo`new FileInputStream(..)`,或者看到我的更新 – Bozho 2011-02-16 12:45:47

2

setCurrentDirectory接受表示一个目录作为参数的文件。不是写入路径的文本文件。

做你想做什么,你要读文件“path.txt”,创建与你刚才读的内容的文件对象,并通过这个文件来setCurrentDirectory:

String pathWrittenInTextFile = readFileAsString(new File("path.txt")); 
File theDirectory = new File(pathWrittenInTextFile); 
fileChooser.setCurrentDirectory(theDirectory); 
相关问题