【问题标题】:How can I read a text file and display it using JoptionPane?如何读取文本文件并使用 JoptionPane 显示它?
【发布时间】:2013-03-21 13:39:39
【问题描述】:

我正在尝试接收用户输入并将其存储在文本文件中,我能够接收输入并将其存储但现在我试图在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;
}

【问题讨论】:

    标签: java swing ioexception java-io


    【解决方案1】:

    您应该使用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;
    }
    

    【讨论】:

    • 谢谢,如果它有多行,我会怎么做?目前它只读取文本文件的一行。
    • 我已经更新了代码以反映读取多行,顺便说一句,我不认为你想从这个函数返回一个字符串。我也删除了它
    猜你喜欢
    • 2015-10-14
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多