Java读取现有文本文档中的内容并输出到文本框
时间: 2023-10-18 14:32:46 浏览: 45
可以使用Java的IO类和GUI类来实现读取现有文本文档中的内容并输出到文本框。
首先,使用IO类中的File和FileReader类来读取文本文档中的内容,如下所示:
```
File file = new File("path/to/file.txt");
FileReader fr = new FileReader(file);
// 读取文本文档中的内容
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = fr.read()) != -1) {
sb.append((char)ch);
}
String content = sb.toString();
fr.close();
```
然后,使用GUI类中的JTextArea类来显示读取到的文本内容,如下所示:
```
JTextArea textArea = new JTextArea();
textArea.setText(content);
```
完整代码示例:
```
import javax.swing.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
// 读取文本文档中的内容
File file = new File("path/to/file.txt");
FileReader fr = new FileReader(file);
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = fr.read()) != -1) {
sb.append((char)ch);
}
String content = sb.toString();
fr.close();
// 显示文本内容到文本框
JTextArea textArea = new JTextArea();
textArea.setText(content);
// 显示文本框
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(textArea));
frame.pack();
frame.setVisible(true);
}
}
```
其中,"path/to/file.txt"需要替换成实际的文本文档路径。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)