简体   繁体   中英

How to store text from JOptionPane into text file

I am a novice. I am trying to take the user-input text from the JOptionPane, and store it into a text file. Thereafter I would like to read the text and do what-not with it.

May I please have help on storing the inputted text? Thanks. Here's my code:

import javax.swing.JOptionPane;
import java.io.*;

public class RunProgram {


public static void introView() {
    //The introduction
    JOptionPane.showMessageDialog(null, "Welcome." +
            " To begin, please click the below button to input some information " +
            "about yourself.");
}

public static void personInput() {

    try{
        File userInfo = new File("C:\\Users\\WG Chasi\\workspace\\" +
                "Useful Java\\products\\UserInfo.txt");
        userInfo.getParentFile().mkdirs();
        FileWriter input = new FileWriter(userInfo);

        JOptionPane userInput = new JOptionPane();
        userInput.showInputDialog("Enter details");/*I want to store the text from the InputDialog into the text file*/
        //Write text from the JOptionPane into UserInfo.txt
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, "An ERROR has occured.");
    }
}


public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            introView();
            personInput();
        }
    });
}

}

You have any number of potential options, depending on your needs...

You could...

Write the contents to a Properties file...

private Properties properties = new Properties();

//...
String name = JOptionPane.showInputDialog("What is your name?");
properties.set("user.name", name);

//...
protected void savePropeties() throws IOException {
    try (OutputStream os = new FileOutputStream(new File("User.properties"))) {
        properties.store(os, "User details");
    }
}

protected void loadPropeties() throws IOException {
    try (InputStream is = new FileInputStream(new File("User.properties"))) {
        // Note, this will overwrite any previously existing
        // values...
        properties.load(is);
    }
}

As you can see, you have to physically load and save the contents yourself. This does mean, however, you get to control the location of the file...

You could...

Make use of the Preferences API...

String name = JOptionPane.showInputDialog("What is your name?");
Preferences preferences = Preferences.userNodeForPackage(RunProgram.class);
preferences.put("user.name", name);

Then you would simply use something like...

Preferences preferences = Preferences.userNodeForPackage(RunProgram.class);
String name = preferences.get("user.name", null);

to retrieve the values.

The benefit of this is the storage process is taking care for you, but you lose control of where the data is stored.

You could...

  • Write the data to a file yourself, in your own format. This is lot of work and overhead, but you gain the benefit of not only controlling the location of the file, but also the format that the data is maintained in. See Basic I/O for some more details.
  • Write the data in XML format, which provides a level of hierarchical control (if that's important), but does increase the complexity of the management.

Try this

     public static void personInput() 
     {

        String whatTheUserEntered = JOptionPane.showInputDialog("Enter details");

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory( new File( "./") );
        int actionDialog = chooser.showSaveDialog(yourWindowName); //where the dialog should render
        if (actionDialog == JFileChooser.APPROVE_OPTION)
        {
            File fileName = new File(chooser.getSelectedFile( ) + ".txt" ); //opens a filechooser dialog allowing you to choose where to store the file and appends the .txt mime type
            if(fileName == null)
                return;
            if(fileName.exists()) //if filename already exists
            {
                actionDialog = JOptionPane.showConfirmDialog(yourWindowName,
                                   "Replace existing file?");
                if (actionDialog == JOptionPane.NO_OPTION) //open a new dialog to confirm the replacement file
                    return;
            }
            try
            {
                BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); 

                    out.write(whatTheUserEntered );
                    out.close(); //write the data to the file and close, please refer to what madProgrammer has explained in the comments here about where the file may not close correctly. 
            }
            catch(Exception ex)
            {
                 System.err.println("Error: " + ex.getMessage());
            }
        }
      }

I am basically attempting to get the text from the input dialog and write it to a file of your choice. The file will be written as a text file using the appending string ".txt" which sets the mime type so will always be text.

Let me know how it goes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM