Reputation: 626
Does Java allow you to import files from a local directory into a program without specifying an actual file? I want the user to choose their own text file to import into my program. I've searched only to find examples on how to read in files with the .txt file already known.
Upvotes: 0
Views: 958
Reputation: 1279
There are multiple ways in which you can allow a user to select a file without actually hard-coding the filename into the program.
Here is one example using the Swing class of JFileChooser
import javax.swing.JFileChooser;
import java.io.File;
public class ChooseFile
{
public static void main(String[] args)
{
// Create JFileChooser
JFileChooser fileChooser = new JFileChooser();
// Set the directory where the JFileChooser will open to
// Uncomment one of these below as an example
// fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
// fileChooser.setCurrentDirectory(new File("c:\\"));
// Show the file select box to the user
int result = fileChooser.showOpenDialog(null);
// Did the user select the "Open" button
if(result == JFileChooser.APPROVE_OPTION)
System.out.println("File chosen: " + fileChooser.getSelectedFile());
else
System.out.println("No file chosen");
}
}
Hope this helps.
Upvotes: 1