用java语言写一个具有编辑,保存和打开文件功能的文本编辑器
时间: 2024-03-12 07:45:29 浏览: 52
好的,我可以为您提供一份Java语言实现的文本编辑器示例代码。以下是基本的代码框架:
```java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextEditor extends JFrame {
private JPanel contentPane;
private JTextArea textArea;
private JFileChooser fileChooser;
private File currentFile;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TextEditor frame = new TextEditor();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TextEditor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 400);
setTitle("Text Editor");
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(scrollPane);
fileChooser = new JFileChooser();
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveFile();
}
});
contentPane.add(btnSave, BorderLayout.NORTH);
JButton btnOpen = new JButton("Open");
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFile();
}
});
contentPane.add(btnOpen, BorderLayout.SOUTH);
}
private void saveFile() {
if (currentFile == null) {
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
currentFile = fileChooser.getSelectedFile();
}
}
if (currentFile != null) {
try {
FileWriter writer = new FileWriter(currentFile);
writer.write(textArea.getText());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void openFile() {
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
currentFile = file;
try {
FileReader reader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
reader.close();
textArea.setText(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这个文本编辑器包括了打开和保存文件的功能。用户可以通过点击“Open”按钮来选择一个文本文件并将其打开到编辑器中,或者通过点击“Save”按钮将编辑器中的文本保存到当前文件或新文件中。您可以根据需要进行修改和扩展。
阅读全文