gpt4 book ai didi

java - 打开、编辑 JTextArea 中的文本并将其保存到 .txt 文件

转载 作者:行者123 更新时间:2023-11-29 10:13:52 25 4
gpt4 key购买 nike

我正在摆弄 java swing,并试图打开一个包含带有 JTextArea 的现有数据的文本文件。无论我尝试了哪些不同的事情,它似乎都没有保存任何更改。

下面的代码可以很好地读取文本文件,但不能写入(很明显)。

如果有人可以告诉我如何成功保存对 JTextArea 的更改,我将不胜感激。

package funwithswing;


import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AllDataGUI extends JFrame{

public AllDataGUI(){
fileRead();
panels();
}

private String storeAllString="";
private JButton saveCloseBtn = new JButton("Save Changes and Close");
private JButton closeButton = new JButton("Exit Without Saving");
private JFrame frame=new JFrame("Viewing All Program Details");
private JTextArea textArea = new JTextArea(storeAllString,0,70);


private JButton getCloseButton(){
return closeButton;
}

private void fileRead(){
try{
FileReader read = new FileReader("CompleteData.txt");
Scanner scan = new Scanner(read);
while(scan.hasNextLine()){
String temp=scan.nextLine()+"\n";
storeAllString=storeAllString+temp;
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}

private void fileWrite(){
try{
FileWriter write = new FileWriter ("CompleteData.txt");
textArea.write(write);
}
catch (Exception e){
e.printStackTrace();
}
}

private void panels(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10));
rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10));
JTextArea textArea = new JTextArea(storeAllString,0,70);
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panel.add(scrollBarForTextArea);
frame.add(panel);
frame.getContentPane().add(rightPanel,BorderLayout.EAST);
rightPanel.add(saveCloseBtn);
rightPanel.add(closeButton);
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frame.dispose();

}
});
frame.setSize(1000, 700);
frame.setVisible(true);
frame.setLocationRelativeTo(null);

}

private void saveBtn(){

}
}

最佳答案

您需要关闭FileWriter。使用 Java-7 的 try-with-resourcefinally block 来正确关闭资源。

private void fileWrite(){
FileWriter write=null;
try{
write = new FileWriter ("CompleteData.txt");
textArea.write(write);
}
catch (Exception e){
e.printStackTrace();
}
finally{
if(write != null)
write.close();
}
}

关于java - 打开、编辑 JTextArea 中的文本并将其保存到 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24076612/

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