I have used the Sun File Chooser Demo to choose files from my desktop or any location.
I have added the following code in the open file action:
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
log.append("Opening: " + file.getName() + "." + newline);
ReadData rd = new ReadData(); //added by me
rd.readData(file.getName()); //added by me
} else {
开发者_如何学Python log.append("Open command cancelled by user." + newline);
ReadData class contains readData method which will take the file name and with BufferedReader will read the contents of the file line by line.
But after choosing the file with file chooser it is not able to open the file from my desktop.If I place the file inside the project folder it is able to open the file without any code change. What modification in code I need to do so that it can choose and open file from any location? Thanks
You are passing only the file's name, not the complete path, to your ReadData
class. So, your ReadData
class is not going to know in which directory the file is - it will try to find it in the current directory (whatever that is at the moment).
Instead of just passing the name of the file, pass the whole path:
rd.readData(file.getPath());
Better yet, change your ReadData.readData()
method so that it takes a File
instead of a String
, and pass it the File
object that you get back from the file chooser:
rd.readData(file);
getName()
only gets the last segment of the file without any path information. If the working directory of your Java application isn't the exact directory that holds that file, that won't work.
Why doesn't your ReadData
just take a file? All file input mechanisms built into Java will accept a File
(e.g. FileInputStream
, FileReader
). Otherwise use getPath()
I guess.
You are only passing the name of the file to the readData() method.
So if your file is stored at C:\Users\JavaBits\Project\Java\file.txt, your readData() method is only getting file.txt so it can't find the file. You should do this:
rd.readData(file);
This will have the relative path in it.
use file object to open inputstream instead using its name. such as:
BufferedReader br = new BufferedReader(new FileInputStream(file));
modify your method readData to accept File object instead String, and use this object to open BufferedReader.
精彩评论