如何阅读文本文件并使用JoptionPane显示它?

时间:2013-03-31 07:03:31

标签: java swing ioexception java-io

我正在尝试接受用户输入并将其存储在文本文件中,我能够接收输入并存储它,但现在我试图在JOptionPane窗口中显示该输入。有人可以帮帮我吗。我是stackflow的新手,这是我的第一篇文章。

/*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;
}

1 个答案:

答案 0 :(得分:0)

您应该使用BufferedReader从文件中读取数据:

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