【问题标题】:How to import data from textfiles to JTextArea?如何将文本文件中的数据导入 JTextArea?
【发布时间】:2011-06-16 23:03:41
【问题描述】:

我有一个包含 10 行信息的文本文件。如何在 JTextArea 中复制粘贴该信息?

public void createPage4()
    {
    panel4 = new JPanel();
    panel4.setLayout( new BorderLayout() );

    BufferedReader log=null;

        try {


        FileReader logg =new FileReader("logsheet.txt");
            log = new BufferedReader(logg); 

        textArea = new JTextArea("how do I get all the content of logsheet, I can get it on the command window as shown below");




        for (int x = 0 ; x<10; x++){

            System.out.println(log.readLine());

             }


             panel4.add(textArea);

【问题讨论】:

  • 无需重新发明轮子。只需使用所有文本组件都支持的 read(...) 方法。

标签: java swing file-io jtextarea


【解决方案1】:

您需要使用Append() 将您阅读的每一行复制到JTextArea 组件的末尾。

追加

public void append(String str) 追加 给定的文本到末尾 文档。如果模型是什么都不做 null 或字符串为 null 或空。 这个方法是线程安全的,虽然 大多数 Swing 方法都不是。请参见 如何使用线程获取更多信息 信息。

参数:str - 要插入的文本 另请参阅:插入(java.lang.String, 整数)

你的 for 循环会变成:

for (int x = 0 ; x<10; x++){
    textArea.append(log.readLine() + "\n");
}

【讨论】:

  • @razshan,请解释一下,当这个功能已经是 API 的一部分时,为什么要编写自己的代码并重新发明轮子?我想如果您需要写入数据,您还将创建自己的 write() 方法,而不是使用 API 中的方法。这不是学习如何编程的方法。
【解决方案2】:
textArea.read(new BufferedReader(new FileReader("logsheet.txt"), null));

【讨论】:

    【解决方案3】:

    类似下面的东西应该可以解决问题:

    BufferedReader reader = new BufferedReader(new FileReader("logsheet.txt"));
    String line;
    while((line = reader.readLine()) != null) {
        textArea.append(line).append("\n");
    }
    reader.close();
    

    在这里,您正在读取文件的全部内容(因此不管它有多少行),将内容附加到字符串构建器,然后将文本区域设置为字符串构建器的内容。 (记住在完成阅读器后关闭阅读器也很重要。)

    以上内容只会附加到文本区域。如果要先清除,在while循环前加上textArea.setText("");

    如果您想确保只读取前 10 行,请添加一个计数器,在 while 循环的每次迭代中将其递增,然后在其为 10 或更高时退出(如果您将其留作实现练习需要它!)

    【讨论】:

      猜你喜欢
      • 2011-10-25
      • 2010-11-17
      • 2011-09-15
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 2020-07-18
      • 1970-01-01
      相关资源
      最近更新 更多