【问题标题】:Java IO: Reading text files as they are seenJava IO:读取所见文本文件
【发布时间】:2012-04-09 02:30:17
【问题描述】:

我有一个包含如下内容的文本文件:

Hello, my name is Joe

What is your name?
My name is Jack.

That is good for you.

唯一的问题是我必须使用 append 方法将它加载到 JTextArea 中才能在 JScrollPane 中显示文本,如下所示:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);

但是当我将文件读入文本区域时,文本区域显示如下:

Hello, my name is JoeWhat is your name?My name is Jack.That is good for you.

BufferedReader 从不将换行符 (\n) 读入 JTextArea。我怎样才能让读者在文件中添加空格和空行?如果有人可以提供帮助,我将不胜感激。谢谢!

【问题讨论】:

  • 如果您使用BufferedReader.readLine() 方法,它会使用它读取的行的行终止字符。因此,您必须在将\n 调用到读取字符串后手动附加它。或者,您可以在缓冲区中使用 BufferedReader.read()stackoverflow.com/questions/4758525/…
  • 贴出您读取文本文件的代码块以便更好地理解。

标签: java swing text io jtextarea


【解决方案1】:

所有 JTextComponents 都能够读取文本文件并写入文本文件,同时完全尊重当前操作系统的换行符,使用它通常是有利的。在您的情况下,您将使用 JTextArea 的 read(...) 方法读取文件,同时充分理解文件系统的本机换行符。像这样:

BufferedReader br = new BufferedReader(new FileReader(file));
textArea.read(br, null);

或者更完整的例子:

import java.io.*;
import javax.swing.*;

public class TextIntoTextArea {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

   private static void createAndShowGui() {
      JFileChooser fileChooser = new JFileChooser();
      int response = fileChooser.showOpenDialog(null);
      if (response == JFileChooser.APPROVE_OPTION) {
         File file = fileChooser.getSelectedFile();
         BufferedReader br = null;
         try {
            br = new BufferedReader(new FileReader(file));
            final JTextArea textArea = new JTextArea(20, 40);

            textArea.read(br, null); // here we read in the text file

            JOptionPane.showMessageDialog(null, new JScrollPane(textArea));
         } catch (FileNotFoundException e) {
            e.printStackTrace();
         } catch (IOException e) {
            e.printStackTrace();
         } finally {
            if (br != null) {
               try {
                  br.close();
               } catch (IOException e) {
               }
            }
         }
      }
   }
}

【讨论】:

  • 那就更好了!非常感谢
【解决方案2】:

读取行时添加换行符。

例如

String output = "";
try {
    BufferedReader br = new BufferedReader(new FileReader(args[i]));
    while ((thisLine = br.readLine()) != null) {
        thisLine += "\n";
        output += thisLine;
    } 
} // end try
catch (IOException e) {
    System.err.println("Error: " + e);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 2017-05-25
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多