gpt4 book ai didi

java - 如何读取文件的内容?

转载 作者:太空宇宙 更新时间:2023-11-04 07:13:25 25 4
gpt4 key购买 nike

我有一个文本编辑器,我将用它来编辑 HTML。我希望能够创建某种文件打开器,它将继续将文本“打印”到文本区域。我不知道我将如何继续做这件事。这是我的代码:

package main;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class TextEditor {
static boolean saved = false;
static final JTextArea textArea = new JTextArea(20,50);
static final JFileChooser chooser = new JFileChooser("save");
static final JFileChooser openChooser = new JFileChooser("Open");
public static void start(){
JFrame f = new JFrame("Text editor");
JPanel savePanel = new JPanel();
JButton sb = new JButton("Save");
JButton qsb = new JButton("Quick save");
JButton ob = new JButton("Open");

sb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
save();
}
});

qsb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quickSave();
}
});

ob.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
open();
}
});

savePanel.add(sb);
savePanel.add(qsb);

f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLayout(new BorderLayout(2,1));
f.add(savePanel,BorderLayout.PAGE_START);
f.add(textArea);
f.pack();
f.setVisible(true);
}

public static void save(){
File dir;
chooser.showDialog(null, "Save");
dir = chooser.getSelectedFile();
System.out.println(dir);
try {
FileWriter fw = new FileWriter(dir);
String text = textArea.getText().replace("\n", System.getProperty("line.separator").toString());
fw.write(text);
fw.close();
saved = true;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
}

public static void quickSave(){
if (saved == false){
JOptionPane.showMessageDialog(null, "You must save at least once to use this function");
}
else{
File dir = chooser.getSelectedFile();
String text = textArea.getText().replace("\n", System.getProperty("line.separator").toString());
try{
FileWriter fw = new FileWriter(dir);
fw.write(text);
fw.close();
}catch(IOException e){
JOptionPane.showMessageDialog(null, e);
}
}
}

public static void open(){
openChooser.showDialog(null, "Oopen");
File dir = openChooser.getSelectedFile();
//want to open file which is dir.
}
}

最佳答案

又好又简单:

textArea.read(new FileReader(dir), null);

这就是全部内容。

关于java - 如何读取文件的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20315936/

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