FileDialog fc=new FileDialog (new Frame(),"Test File Dialog");
fc.setVisible(true);
String selectedFile=fc.getFile();
File file = new File(selectedFile);
String absolutepath = file.getAbsolutePath();
hi, am trying to get the full file path of a text file. the file is in a different folder outside my java project folder but on the same drive. when i try to open it with the above code, am getting开发者_JS百科 the correct file name in SelectedFile but file.getAbsolutePath() is doesnot return the correct file location. file.getAbsolutePath() is returning my java project's folder.
Please help me get the correct file location for any file i select in the File Dialogue
Any particular reason for sticking to AWT?
Otherwise I suggest you use a JFileChooser
dialog instead. Here are a few related links to help you get started on that:
- Example Depot: Creating a JFileChooser
- Official Trail: How to Use File Choosers
- API Documentation
From the doc's for java.io.File:
By default the classes in the java.io package always resolve relative pathnames against the current user directory.
You are only retrieving the name of the file (a relative path) from the dialog - not the full path (absolute). When you create the file object on line 4 it expects the file to exist in the current directory.
Use the following instead:
String selectedFile=fc.getFile();
String selectedDirectory=getDirectory();
File file = new File(selectedDirectory, selectedFile);
精彩评论