如何将JOptionPane中的文本存储到文本文件中

时间:2014-12-24 23:39:23

标签: java file io

我是新手。我试图从JOptionPane获取用户输入文本,并将其存储到文本文件中。此后,我想阅读文本,不做任何事情。

我可以帮忙存储输入的文字吗?谢谢。 这是我的代码:

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();
        }
    });
}

}

2 个答案:

答案 0 :(得分:3)

根据您的需要,您有多种潜在选择......

你可以......

将内容写入Properties文件...

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);
    }
}

如您所见,您必须亲自加载并保存内容。但这确实意味着您可以控制文件的位置......

你可以......

使用Preferences API ...

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

然后你会简单地使用像...这样的东西。

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

检索值。

这样做的好处是存储过程正在照顾您,但您无法控制数据的存储位置。

你可以......

  • 以您自己的格式自行将数据写入文件。这需要大量工作和开销,但您不仅可以获得控制文件位置的好处,还可以获得维护数据的格式。有关更多详细信息,请参阅Basic I/O
  • 以XML格式编写数据,这提供了一定程度的分层控制(如果这很重要),但确实增加了管理的复杂性。

答案 1 :(得分:1)

试试这个

     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());
            }
        }
      }

我基本上是尝试从输入对话框中获取文本并将其写入您选择的文件中。该文件将使用附加字符串" .txt"作为文本文件写入。设置mime类型所以将始终是文本。

让我知道它是怎么回事。