簡體   English   中英

如何將文本從JOptionPane存儲到文本文件中

[英]How to store text from JOptionPane into text file

我是新手。 我正在嘗試從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();
        }
    });
}

}

根據您的需要,您有許多潛在的選擇...

你可以...

將內容寫入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格式編寫數據,該格式提供了層次控制(如果重要的話),但是確實增加了管理的復雜性。

嘗試這個

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

我基本上是試圖從輸入對話框中獲取文本並將其寫入您選擇的文件中。 該文件將使用設置了mime類型的附加字符串“ .txt”作為文本文件寫入,因此始終為文本。

讓我知道事情的后續。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM