我收到了有关如何附加文本文件的帮助,但现在看来我已经破坏了其他东西。我无法“读取”该文件。
我想做的是:
- 从 GUI 文本字段输入数据
- 单击保存按钮(创建文件并将数据附加到 .txt 文件)
- 能够从文件读回面板
我又在做蠢事了,我害怕。
下面是我的 GUI、CreateTextFile 和 ReadTextFile 的 java 代码
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JButton saveButton;
private JButton openButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 525;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Wounded Warrior Donation Tracker.");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
results.setEditable(false);
results.setWrapStyleWord(true);
results.setLineWrap(true);
results.setBorder(BorderFactory.createLoweredBevelBorder());
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
saveButton = new JButton ("Save");
saveButton.addActionListener(new SaveButtonListener());
openButton = new JButton ("Open");
openButton.addActionListener(new OpenButtonListener());
// Create a panel.
panel = new JPanel();
panel.setBackground(Color.orange);
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(clearButton);
panel.add(saveButton);
panel.add(openButton);
panel.add(exitButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if (donationAmt(pledgeField.getText())) {
donationAmt[i] = Double.parseDouble(pledgeField.getText());
}else{
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
i++;
}
}
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //checking for empty field
JOptionPane.showMessageDialog(null, "Please enter amount pledged");
return false;
}
for(int i = 0; i < amount.length(); i++){ //verifying dollar amount entered as number
if (!Character.isDigit(amount.charAt(i)) && amount.charAt(i)!='.'){
JOptionPane.showMessageDialog(null, "Invalid input.");
return false;
}
}
return true;
}
private class ClearButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private class SaveButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
CreateTextFile cr = new CreateTextFile();
cr.openFile();
cr.addRecords(donorName, charityName, donationAmt);
cr.closeFile();
JavaDBClass db = new JavaDBClass();
}
}
private class OpenButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ReadTextFile read = new ReadTextFile();
read.openFile();
DonorGUI donor = read.readRecords();
read.closeFile();
JavaDBClass db = new JavaDBClass(donor);
for(int i = 0;i<donor.donationAmt.length;i++){
try {
results.append(db.showTable()[i]+"\n");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
创建文本文件 JAVA 代码:
/** This will create a text file based on user input and save it as donations.txt.
*
*/
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
public class CreateTextFile {
//object that outputs text to a file
private Formatter output;
//try opening a file
public void openFile(){
try
{
output = new Formatter(new FileOutputStream("C:/temp/donations.txt", true));
}
catch (SecurityException securityException)
{
System.out.println("You cannot write to this file.");
}
catch (FileNotFoundException notFoundException)
{
System.out.println("You couldn't open or find the file.");
}
}
//try writing to the file
public void addRecords(String[] donor, String[] charity, double[] donation){
try{
for (int j=0; j<donor.length; j++) {
if (donor[j] != null) {
output.format("\n%s %s %.2f",donor[j],charity[j],donation[j]);
}
}
}
catch (FormatterClosedException formatterClosedException){
System.out.println("You couldn't write to this file.");
}
catch (NoSuchElementException elementException){
System.out.println("Invalid Input.");
}
}
//try closing the file
public void closeFile(){
if(output!=null)
output.close();
}
}
阅读文本文件 JAVA 代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadTextFile {
private Scanner input;
//try to open the file
public void openFile(){
try{
input = new Scanner(new File("C:/temp/donations.txt"));
}
catch (FileNotFoundException fileNotFoundException)
{
System.out.println("File not found.");
System.exit(1);
}
}
//try to read from the file
public DonorGUI readRecords(){
DonorGUI gui = new DonorGUI();
while(input.hasNext())
{
for(int j = 0;j<20;j++){
gui.donorName[j] = input.next();
gui.charityName[j] = input.next();
gui.donationAmt[j] = input.nextDouble();
}
}
return gui;
}
//try to close the file
public void closeFile(){
if(input!=null)
input.close();
}
}
收到的错误:
Exception in thread "AWT-EventQueue-0" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at ReadTextFile.readRecords(ReadTextFile.java:39)
at DonorGUI$OpenButtonListener.actionPerformed(DonorGUI.java:191)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6288)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6053)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4651)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:616)
at java.awt.EventQueue$2.run(EventQueue.java:614)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 8 seconds)