How To Open File Dialog And Create File On It? - java

1
I opened File Dialog but I don't create the file on it? How?
JFileChooser fileChooser = new JFileChooser();
File selectedFile = null;
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (**result == JFileChooser.APPROVE_OPTION**) {
selectedFile = fileChooser.getSelectedFile();
} else {
confirmExit();
return;
}

To save a file with JFileChooser, you need to use the showSaveDialog() method instead of the showOpenDialog() like in your snippet. For more information check out How to use File Choosers and check out the JFileChooser JavaDoc.
Then the next step if the saving has been approved, is to actually write the file.
For this, you can use a FileWriter.
I put together a small snippet, which opens a JFileChooser on a button click, where you can provide the filename, where some String will be written to this file.
Example:
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> buildGui());
}
private static void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("Save your File");
// action listener for the button
btn.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser(); // create filechooser
int retVal = fileChooser.showSaveDialog(frame); // open the save dialog
if (retVal == JFileChooser.APPROVE_OPTION) { // check for approval
// create a bufferedwriter with the specified file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {
// write the content to the file
writer.write("Your content that shall be written to the file");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
panel.add(btn);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Output:

Related

Java Swing File and Folder Choose

Hi I am new to swing and I need some help. I have build a file processing project where I read an input file and some other existing files in the project, do many checks and parsing and produce a csv and an xlsx file. Until now I used for these inputs
JTextField csvpath = new JTextField();
JTextField csvfile = new JTextField();
JTextField xmlpath = new JTextField();
JTextField xmlfile = new JTextField();
JTextField excpath = new JTextField();
JTextField excfile = new JTextField();
Object[] message = {
"Enter the path of the CSV file to be created:", csvpath,
"Enter the CSV file name:", csvfile,
"Now enter the XML path to be read:", xmlpath,
"Also enter the XML file name:", xmlfile,
"Please enter the Excel file path to be created:", excpath,
"Finally enter the Excel file name:", excfile
};
int option = JOptionPane.showConfirmDialog(null, message, "Convert XML File to CSV File", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
String csvPath = csvpath.getText();
String csvFileName = csvfile.getText();
String xmlPath = xmlpath.getText();
String xmlFileName = xmlfile.getText();
String excPath = excpath.getText();
String excFileName = excfile.getText();
String FullcsvPath = csvPath + "\\" + csvFileName + ".csv";
String FullxmlPath = xmlPath + "\\" + xmlFileName + ".xml";
String excelPath = excPath + "\\" + excFileName + ".xlsx";
.
.
parsing/creating starts...
Because in the future this project will be used by others I wanted to create file chooser and get the file/folder paths as strings in order to read the input and create etc...
I have created a class and public strings for paths and when I call it the program does not stop like before, continues to run while the Frame is open without getting the paths I want. My new class is:
public static void SelectFiles() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
final JFrame window = new JFrame("Parse for manufacturers - Developed by Aris M");
JPanel topPanel = new JPanel();
JPanel midPanel = new JPanel();
JPanel botPanel = new JPanel();
final JButton openFolderChooser = new JButton("Select Folder to save csv - xlsx results");
final JButton openFileChooser = new JButton("Select the File to be parsed");
final JButton closeButton = new JButton("OK");
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
final JFileChooser fc = new JFileChooser();
openFolderChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (fc.showOpenDialog(openFolderChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
csv = fc.getSelectedFile().getAbsolutePath();
xlsx = csv;
System.out.println(csv);
}
}
});
openFileChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setCurrentDirectory(new java.io.File("user.home"));
fc.setDialogTitle("This is a JFileChooser");
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(openFileChooser) == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(null, fc.getSelectedFile().getAbsolutePath());
System.out.println(fc.getSelectedFile().getAbsolutePath());
xml = fc.getSelectedFile().getAbsolutePath();
System.out.println(xml);
}
}
});
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
window.dispose();
}
});
window.add(BorderLayout.NORTH, topPanel);
window.add(BorderLayout.CENTER, midPanel);
window.add(BorderLayout.SOUTH, botPanel);
topPanel.add(openFolderChooser);
midPanel.add(openFileChooser);
botPanel.add(closeButton);
window.setSize(500, 150);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
Swing code runs in separate thread known as the event dispatch thread. Just make your main thread busy while frame is visible. Add following code to the end of SelectFiles() method:
while (window.isVisible()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Files are showing selected file after opening the dialog box in jfilechooser multi file chooser enabled

I am dealing with this swing component JfileChooser . I am selecting multiple file and then clicked ok .
After that if i again open to select the file it is showing me the previous selected file which i dont want .
I want previous directory to be maintained but not the previous files .It gives very Bad User experience .
Here is the code Snippet what i have written.
JFileChooser fileopen = new JFileChooser();
private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileButtonActionPerformed
fileopen.setMultiSelectionEnabled(true);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File[] file = fileopen.getSelectedFiles();
fileText.setText(file[0].getAbsolutePath());
for( int i =1;i < file.length;i++)
{
fileText.append("||");
fileText.append(file[i].getAbsolutePath());
}
}else {
log.info("File access cancelled by user.");
}
}//GEN-LAST:event_fileButtonActionPerformed
I tried with those setcurrentdirecotory and all . Any help will be appreciated.
Either create a new instance of JFileChooser each time you need it or call setSelectedFiles and pass it null
Updated
So, I had a quick look at the setSelectedFile and setSelectedFiles methods and they should be clearing the selection and the "file name" field, but it doesn't seem to be working for me on Mac OS, so it's likely a look and feel issue.
What I tend to do is cheat. I store the last directory value in the Preferences API, I do this because it's super easy and it also means that the value persists across executions, super helpful. If you don't want to persist it across executions, you could use a Map or Properties or some other variable, that's up to you
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("...");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileopen = new JFileChooser();
String path = Preferences.userNodeForPackage(TestPane.class).get("FileAccess.lastSelectedDirectory", null);
if (path != null) {
File filePath = new File(path);
if (filePath.exists() && filePath.isDirectory()) {
fileopen.setCurrentDirectory(filePath);
}
}
fileopen.setMultiSelectionEnabled(true);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File[] file = fileopen.getSelectedFiles();
System.out.println("You selected " + file.length + " files");
Preferences.userNodeForPackage(TestPane.class).put("FileAccess.lastSelectedDirectory", fileopen.getCurrentDirectory().getAbsolutePath());
} else {
System.out.println("File access cancelled by user.");
}
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}

Java program not saving contents of ".txt" file

I am working on a text editor in Java as a fun side project. When I exported the project, I converted to executable JAR file to ".exe" so that I could set the text editor as the default program to open ".txt" files. I can run the ".exe" and write text and then save the file, and the file saves, but the contents of the file are not saved when I try to open the file with the text editor; however, I can open the same file with notepad, and the contents of the file show. The file saves fine in Eclipse. What do I need to fix so that the file contents are shown when I try to open them with my text editor?
Here is my code:
public class Open extends JFrame implements KeyListener {
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JMenuBar menuBar = new JMenuBar();
JMenu menu;
JMenuItem item;
Font systemFont;
public Open() {
systemFont = new Font("Times New Roman", Font.PLAIN, 20);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(false);
textArea.setFont(systemFont);
panel.setLayout(new BorderLayout());
panel.add(scrollPane);
add(panel);
menu = new JMenu("File");
item = new JMenuItem("Save As");
item.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
menu.add(item);
menuBar.add(menu);
menu = new JMenu("Edit");
item = new JMenuItem("Undo");
menu.add(item);
menu.add(item);
menuBar.add(menu);
add("North", menuBar);
setLookAndFeel();
frameDetails("Text Editor");
}
public void frameDetails(String title) {
setSize(700, 500);
setLocationRelativeTo(null);
setTitle(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setLookAndFeel() {
try {
UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Open editor = new Open();
}
}
Here is the bit of code with the save button:
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
You are never reading the text file. In order to do that, Use something like this
public void loadFile(JTextArea area, String path, String file)
{
try
{
area.read(new FileReader(path + file), "Default");
}
catch(IOException e)
{
e.printStackTrace();
}
}
Note: You don't have to have this in a method. You could just use the try - catch code
To act as a default text editor, your program needs to accept a file name as the argument to main (String[] args). It should verify the file exists, then open it, read its contents, and close it.
Also, when you save a file you should rename the former version to "name.bak" or "name~" before overwriting it with the new version, in case something goes wrong during the save.

JFileChooser component display weird

I'm trying to open a file in filechooser dialog, however, when i opened a file or simply close the dialog. The dialog appears again, i have to close it twice. Here is my code, don't know what's wrong with it
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
ObjectInputStream input;
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
this code lines to create first one
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
and rest of code lines to embeding second one
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
Remove the first occurrence of openFileChooser.showOpenDialog(null);

Unable to figure how to store "Save As" text in a string and use it

I am new to UI design in Java. I am trying to create a GUI to download a file off the Internet and save it on your hard drive. I have got the code working except for one thing which I want to add. I have added a JFileChooser which lets the user select the destination folder. But I am unable to figure out how to change the filename to the one which user enters in the Save As bar on the JFileChooser menu.
Browse Button
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}
});
Download Button
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(DESTINATION_FOLDER + "/" + filename);
Here filename should be the one which user enters. Pointers on how to get this done?
Actually you don't need to get the FileName from the Save As Bar in the JFileChooser.
Just do like this:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
//Don't use the 'FileSelectionMode();'. Let it be Default.
chooser.setAcceptAllFileFilterUsed(true);
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
file = chooser.getSelectedFile();
//file should be declared as a File.
System.out.println("The location to save is: " + chooser.getCurrentDirectory();));
System.out.println("The FileName is: " + file.getName());
}
}
DOWNLOAD BUTTON:
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(file);
Without seeing more of your code the best I could suggest is to create a Global String in the class you are working in.
public class gui extends JFrame{
public String filePath="";
public static void main(String args[]){
//button code
browseButton.addActionListener(new ActionListener())
saveAsButton.addActionListener(new ActionListener())
URLConnection connection = downloadUrl.openConnection();
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("browseButton"){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: "+chooser.getCurrentDirectory());
filePath = chooser.getCurrentDirectory().toString();
}
else{
//save as button selected
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(filePath);
}
}
}
Add this line:
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
Full code:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}

Categories