Simple way to choose a file - java

Is there some simple way to choose a file path in Java? I've been searching around, and JFileChooser keeps coming up, but that's already too excessive for what I want now, as it seems to require making a whole GUI just for that. I'll do it if need be, but is there a simpler way to get the file path?
I'm wondering if there's something like a JOptionPane dialog box to search for the file path.

When you have no surrounding UI, you can simply use this (based on the Answer from Valentin Montmirail)
public static void main( String[] args ) throws Exception
{
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog( null );
switch ( returnValue )
{
case JFileChooser.APPROVE_OPTION:
System.out.println( "chosen file: " + fileChooser.getSelectedFile() );
break;
case JFileChooser.CANCEL_OPTION:
System.out.println( "canceled" );
default:
break;
}
}

Here is the simpliest way to choose a file path in Java :
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(YourClass.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
} else {
log.append("Open command cancelled by user." + newline);
}
} ...
}
You can plug this actionPerformed to a button for example, and that's it. Your button will open a GUI to select a file, and if the user select the file JFileChooser.APPROVE_OPTION, then you can perform the action that you want (here only logging what was opened)
See the oracle documentation (https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) if you want to do something else (not binding a button ?) or something more complex (filter for some extensions only ? ...)

JFileChooser is not that complicated if you only need to choose a file.
public class TestFileChooser extends JFrame {
public void showFileChooser() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
}
public static void main(String args[]) {
new TestFileChooser().showFileChooser();
}
}

Related

Why can't I pass my 'file' variable to actionPerformed?

I am trying to write a Java GUI that takes a file containing song information, allows the user to edit it, then outputs the new file with the same name. The file pathway is supplied by a run-time parameter, so the user would run the program like:
java myProgram myFile
This is how I am initializing the file in the main method (I am assuming since the file pathway is input as a run-time parameter, it must be assigned to a variable in the main method. I am not sure if I am correct):
public class SongDatabase extends JFrame
{
public SongDatabase(File file) throws IOException
{
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new Panel(file);
this.add(panel);
}
public static void main (String [] args) throws IOException
{
File file = null;
if (args.length == 1)
{
file = new File(args[0]);
}
else
{
System.out.print("No source file entered. Create source file (1 for yes 2 for no)?");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice ==2)
{
System.exit(0);
}
else
{
file.createNewFile();
}
}
JFrame frame = new SongDatabase(file);
frame.setVisible(true);
}
}
Upon selecting an "exit" button in the GUI, the program should take the stored data and output it using the same file pathway (basically overwriting the old file). Whatever I try, I can't seem to pass 'file' to the actionPerformed method, where this should be taking place. Based on responses from other questions about passing arguments to the actionPerformed this is what I tried in an attempt to get this to work:
public class Panel extends JPanel implements ActionListener{
...
File myFile;
public Panel(File file) throws IOException {
myFile = file;
...
}
public void actionPerformed(ActionEvent e) {
...
if (source == exitButton) {
try (PrintWriter outFile = new PrintWriter(myFile))
{
for (int i = 0; i < songBox.getItemCount(); i++)
{
Song songOut = songList.get(i);
outFile.println(songOut.getSongName()+ "\t" + songOut.getSongCode()+ "\t" + songOut.getSongArtist()+ "\t"+ songOut.getSongAlbum()+ "\t" + songOut.getSongPrice());
}
}
System.exit(0);
}
}
but that doesn't seem to work. For whatever reason, I get a FileNotFoundException. Are there any better alternatives to passing 'file' to actionPerformed?
Edit: I know it's not the path name or file that is the problem because when the offending code is removed the program imports the file correctly and runs as expected. When debugging the code, myFile does have the correct path so I would think that it should work fine, but it doesn't.

How can I get a variable from a method in java without invoking said method?

I'm coding a small audio player and need help here; the method fopen() is called by a button press in another class (not the issue here); the problem is that I cannot get the file's path as a string without calling the method.
The playsound() method needs the filepath variable from fopen(), and if I use the String 'path' (initialized after fopen()) it calls the method again.
I ONLY need the 'filepath' variable, but I cannot access it outside of fopen(), or at least not that I know of. Assistance on how I can access filepath without invoking fopen()?
EDIT: Fixed fopen() being set up to return a 'File' instead of a string. Also made some changes to the code; the issue of having fopen() called when it's not supposed to be is fixed, but now it gives me a java.io.FileNotFoundException: when I call playsound() (which, from what I understand, means that the file's path and/or name wasn't even recorded). What else is going on here?
Edit 2: I'm just going to ask another question, seeing as the problem at hand seems to have been answered, and I have an entirely different one on my hands.
package mediaz;
import javazoom.jl.player.*;
import javax.swing.filechooser.*;
import java.io.*;
import javax.swing.JFileChooser;
public class audio {
private String lastfilepath = "";
public String fopen(){
JFileChooser fc= new JFileChooser();
FileNameExtensionFilter filtermp3 = new FileNameExtensionFilter("MPEG-2
Audio Layer III", "mp3");
fc.setFileFilter(filtermp3);
int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
String filepath = file.getAbsolutePath();
this.lastfilepath = filepath;
return filepath;
}
else
return null;
}
String path = fopen();
void playsound(){
System.out.println("You pressed play.");
try{
FileInputStream fis = new FileInputStream(this.lastfilepath);
Player playMP3 = new Player(fis);
playMP3.play();
}
catch(Exception e){
System.out.println("Error: '" + e +"'");
}
}
// IGNORE WHAT'S BELOW HERE //
void rewsound(){
System.out.println("You pressed rewind.");
}
void pausesound(){
System.out.println("You pressed pause.");
}
/* void forwardsound(){
System.out.println("You pressed fast forward.");
}
*/
}
Create a String instance variable in audio, and then when you call fopen() store the currently selected file's path in that string.
See code below. Untested, but the idea is here. Also, the formatting of this code is pretty bad, it's hard to read. This is what it should look like (ish).
Edit: Added some comments in the code on general improvements/coding style
Edit: For more info on the try I updated in the code, see: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
package mediaz;
import javazoom.jl.player.*;
import javax.swing.filechooser.*;
import java.io.*;
import javax.swing.JFileChooser;
public class audio {
private String filePath = "";
public File fopen() {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filtermp3 = new FileNameExtensionFilter("MPEG-2
Audio Layer III ", "
mp3 ");
fc.setFileFilter(filtermp3); int ret = fc.showOpenDialog(null);
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
this.filePath = file.getAbsolutePath()
return filepath; // should be file
} else // give me braces please!
return null;
}
// try to stick to camelCase, it is the 'Java' way
void playsound() {
System.out.println("You pressed play.");
// streams implement AutoCloseable, use it
// also, you were not closing fis as it was
try (FileInputStream fis = new FileInputStream(this.filePath)) {
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println("Error: '" + e + "'");
}
}
}
Your fopen() method is declared to return a File, yet in the method you return a String. If you returned the file that the user selected, and then stored this reference somewhere, you could ask that file for its path any time you wanted.
Create another method that returns the last filepath determined in fopen(), eg:
private String lastFilepath;
public String fopen() {
// logic for determining filepath
lastFilepath = filepath;
return filepath;
}
public String getLastFilepath() {
return lastFilepath;
}
First of all you should read about scopes in java programming.
What you currently have is a local scope for your variable "filepath". To make it accessible outside its method block you can either return it as the method result or asign it to a instance variable.
In addition please note that your fopen() method currently won't compile cause it is declared to return a File but inside tries to return a String type.
I would recommend the following:
public class foo {
private String filePath;
private void readFile() {
filePath = doReadingHere();
}
private void useFilePath() {
System.out.println(filePath);
// do what ever you like to do with the instance variable filePath
}
}

In java the JFileDialog box will not appear multiple times

On my computer this block of code will only show the JFileChooser once instead of multiple times. (Im on a Mac)
I need to be able to show the dialog multiple times.
public class FileManager {
public static void main(String args[]) {
showDirectoryDialog();
System.out.println("BLOCKING");
showDirectoryDialog();
System.out.println("BLOCKING");
}
public static File showDirectoryDialog() {
System.out.println("Creating dialog");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(null);
System.out.println("Dialog done");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
return f;
}
return null;
}
}
EDIT:
This does work if I create a static instance of JFileChooser and persist it.
does anyone know why this behaviour exists?
EDIT2:
I am using OSX 10.9.4
And I checked to make sure the second dialog box was not at the behind any other programs.
(unless they hid it behind the desktop lol)

JFileChooser not showing up

I have a method that takes a txt file as an input. I used to use string by typing the direct path to the file.
But it became burdensome whenever I tried to use different file for an input. I try implementing JFileChooser but with no luck.
This is the code, but nothing happening.
public static JFileChooser choose;
File directory = new File("B:\\");
choose = new JFileChooser(directory);
choose.setVisible(true);
File openFile = choose.getSelectedFile();
FileReader fR = new FileReader(openFile);
BufferedReader br = new BufferedReader(fR);
As per Java tutorial on How to Use File Choosers:
Bringing up a standard open dialog requires only two lines of code:
//Create a file chooser
final JFileChooser fc = new JFileChooser();
...
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);
The argument to the showOpenDialog method specifies the parent
component for the dialog. The parent component affects the position of
the dialog and the frame that the dialog depends on.
Note as per docs it can also be:
int returnVal = fc.showOpenDialog(null);
If the parent is null, then the dialog depends on no visible window,
and it's placed in a look-and-feel-dependent position such as the
center of the screen.
 
Also have a read on Concurrency in Swing if you haven't already.
No blocking code (as David Kroukamp suggest). It solves "not showing up" problem.
Runnable r = new Runnable() {
#Override
public void run() {
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if( jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ){
selected = jfc.getSelectedFile();
}
}
}
SwingUtilities.invokeLater(r);
I personally found that the first dialog would show, but subsequent dialogs wouldn't show. I fixed it by reusing the same JFileChooser with this code.
JFileChooser jfc = new JFileChooser();
File jar = selectFile(jfc, "Select jar to append to");
File append = selectFile(jfc, "Select file to append");
//When done, remove the window
jfc.setVisible(false);
public static File selectFile(JFileChooser jfc, String msg) {
if (!jfc.isVisible()) {
jfc.setVisible(true);
jfc.requestFocus();
}
int returncode = jfc.showDialog(null, msg);
if (returncode == JFileChooser.APPROVE_OPTION) return jfc.getSelectedFile();
return null;
}
For JFileChoosers, you're supposed to call objectName.showOpenDialog(Component parent) or objectName.showOpenDialog(Component parent). These methods will return an integer, which you can use to compare to the static constants set in JFileChooser to determine whether the user clicked cancel or open/save. You then use getSelectedFile() to retrieve the file that the user has selected.
Ex (There might be small errors):
class Example {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
File selected;
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selected = jfc.getSelectedFile();
}
}
}
The Java API is a great resource for figuring out what objects can do what, and how. Here's the page for JFileChoosers
The API pages are usually found when you Google the object name. They're usually the first ones that come up as a result as well.

JFileChooser Help

I am trying to set the file filter for my JFileChooser. This is my code:
JFileChooser picker= new JFileChooser();
picker.setFileFilter(new FileNameExtensionFilter("txt"));
int pickerResult = picker.showOpenDialog(getParent());
if (pickerResult == JFileChooser.APPROVE_OPTION){
System.out.println("This works!");
}
if (pickerResult == JFileChooser.CANCEL_OPTION){
System.exit(1);
}
When I run my program, the file chooser comes up, but it won't let me pick any .txt files. Instead, it says this in the console:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Extensions must be non-null and not empty
How do i fix this?
You need to add at least one extension as a second paramter. From the API:
FileNameExtensionFilter(String description, String... extensions)
Parameters:
description - textual description for the filter, may be null
extensions - the accepted file name extensions
Also if you want an specific files extensions and navigate thru folders you can try this:
JFileChooser fc = new JFileChooser(path);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.addChoosableFileFilter(new FileFilter () {
#Override
public String getDescription() {
return "DAT Files";
}
#Override
public boolean accept(File f) {
if (f.isDirectory())
return true;
return f.getName().endsWith(".dat");
}
});
fc.setAcceptAllFileFilterUsed(false);

Categories

Resources