Java file dialog


 

Java file dialog

In this section, you will learn how to display a dialog window through which user can select a file.

In this section, you will learn how to display a dialog window through which user can select a file.

Java file dialog

In this section, you will learn how to display a dialog window through which user can select a file.

Description of code

Irrespective of JFileChooser, there is one another way to select a file from the file system. The package java.awt.* has provided this utility by introducing the class FileDialog that displays the  modal dialog. It blocks the rest of the application until the user has chosen a file.

You can see in the given code, we have created an instance of FileDialog class and through its object we have called setDirectory("C:/") method. This method opens the dialog with the specified directory. The method getFile() returns the selected file. This selected file along with the directory name is then passed to the File object. The FileWriter class along with BufferedWriter class is then used this file object and write data into the selected file using write() method.

Here is the code:

import java.io.*;
import java.awt.*;

public class JavaFileDialog {
	public static void main(String[] args) throws Exception {
		FileDialog fc = new FileDialog(new Frame(), "File Dialog");
		String dir = "C:/";
		fc.setDirectory(dir);
		fc.setVisible(true);
		String selectedFile = fc.getFile();
		System.out.println("You have selected: " + selectedFile);
		File f = new File(dir + selectedFile);
		BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
		bw.write("Hello World");
		bw.close();
	}
}

Through the above code, you can select any file from the file system. The FileDialog opens the dialog to select any file.

Ads