Java IO:阅读文本文件

时间:2012-03-25 03:21:06

标签: java swing text io jtextarea

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

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。如何让读者添加文件中出现的空格和空白行?如果有人可以提供帮助,我会很感激。谢谢!

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

读取行时附加换行符。

例如

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