Java IO:读取所看到的文本文件

Java IO:读取所看到的文本文件,java,swing,text,io,jtextarea,Java,Swing,Text,Io,Jtextarea,我有一个文本文件,其中包含如下内容: Hello, my name is Joe What is your name? My name is Jack. That is good for you. Hello, my name is JoeWhat is your name?My name is Jack.That is good for you. 唯一的问题是,我必须使用append方法将其加载到JTextArea中,以便在JScrollPane中显示文本,如下所示: JTextAre

我有一个文本文件,其中包含如下内容:

Hello, my name is Joe

What is your name?
My name is Jack.

That is good for you.
Hello, my name is JoeWhat 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 Joe

What is your name?
My name is Jack.

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

BufferedReader从不将换行符(\n)读入JTextArea。我如何让读者添加文件中出现的空格和空行?如果有人能帮忙,我将不胜感激。谢谢

读取行时追加换行符

比如说

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

所有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) {
               }
            }
         }
      }
   }
}

如果使用
BufferedReader.readLine()
方法,它将使用所读取行的行终止字符。因此,在将
\n
调用到读取字符串中后,必须手动将其追加。或者,您可以将
BufferedReader.read()
改为使用到缓冲区中。发布你的代码块来读取文本文件,以便更好地理解。那就更好了!非常感谢你