Java IO:阅读文本文件 [英] Java IO: Reading text files as they are seen

查看:139
本文介绍了Java IO:阅读文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text file which contains something like this:

Hello, my name is Joe

What is your name?
My name is Jack.

That is good for you.

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

The only problem is that I have to load it into a JTextArea with the append method to display the text in a JScrollPane like so:

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

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

But when I read the file into the text area, the text area displays something like this:

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

BufferedReader永远不会将换行符(\ n)读入JTextArea。如何让读者添加文件中出现的空格和空白行?如果有人可以提供帮助,我会很感激。谢谢!

The BufferedReader never reads in newlines (\n) into the JTextArea. How could I make the reader add the spaces and blank lines as they appear in the file? If anyone can help I would appreciate it. Thanks!

推荐答案

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

All JTextComponents have the ability to read in text files and write to text files while fully respecting the newline character for the current operating system, and it is often advantageous to use this. In your case, you would use the JTextArea's read(...) method to read in the file while fully understanding the file system's native new-line character. Something like so:

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

这篇关于Java IO:阅读文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆