简体   繁体   中英

How can I read a text file and display it using JoptionPane?

I am trying to take in user input and storing it in a text file, I was able to take in the input and storing it but now i am trying to display that input in a JOptionPane window. Can someone please help me. I am new on stackflow and this is my first post.

/*Here i am taking in user input and storing it in a file called "dictionary.txt".*/
public static String addNewWord()throws IOException
{
    String newWord = "";

    newWord = JOptionPane.showInputDialog(null, "Enter the word you want to add to your dictionary.");

    FileWriter aDictionary = new FileWriter("dictionary.txt", true);
    PrintWriter out = new PrintWriter(aDictionary);
    out.println(newWord);
    out.close();
    aDictionary.close();

    return newWord;
}
/* Now i am trying to read "dictionary.txt" and display it using JOptionPane*/
public static String listDictionary()throws IOException
{
   FileReader aDictionary = new FileReader("dictionary.txt");
   String aLineFromFile = FileReader;
   JOptionPane.showMessageDialog(null, aLineFromFile);
   aDictionary.close();

   return aLineFromFile;
}

You should use a BufferedReader to read the data back from the file:

public static void listDictionary()throws IOException
{
    BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
    String aLineFromFile = null;
    while ((aLineFromFile = br.readLine()) != null){
            JOptionPane.showMessageDialog(null, aLineFromFile);
    }        
    br.close();
    return;
}

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