gpt4 book ai didi

JavaIO : Reading text files as they are seen

转载 作者:行者123 更新时间:2023-12-01 19:19:25 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于JavaIO : Reading text files as they are seen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9857688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com