次のようなテキスト ファイルがあります。
Person1 名前
Person1 年齢
Person1 住所
Person2 名前
Person2 年齢
Person2 住所
Person3 名前
Person2 年齢
Person3 住所
データベースに情報を取得する必要があります。
私はデータベース接続を持っており、行を正しい変数に入れたらデータベースに情報を入力する方法を知っています。. . しかし、Java で新しい行をそれぞれ識別し、情報を変数に設定するにはどうすればよいでしょうか。
基本的に、テキストファイル情報を取得して、次の変数に追加する必要があります
$名前
$年齢
$住所
配列を使おうと思ったのですが、文字列と数値が混在しているので文字列配列が使えません。
Line per line を使用しているため、区切り記号はありません。
**更新情報**
名前、年齢、住所を変数の例として使用し、いくつかの回答が機能するようになりましたが、まだ完全に機能していないため、コード全体を投稿する必要があります。. .
私はコードのクリーンアップにもオープンです (Java は初めてです)。
リーダーが変数をスペースで区切っており、名前とアドレスのような状況では両方にスペースが含まれていることを除いて、私が与えられた答えはうまくいきました.スペース区切り文字は私が必要とする結果を与えていません.
テキストファイルの内容は次のとおりです。
レイ・ウェイド
200
米国エイズ児童基金トム・ハーディ
125.50
アメリカ赤十字社
ご覧のとおり、LoadTextFile(); を呼び出します。CreateTables() 関数内
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.sql.*;
import javax.sql.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Charity extends JFrame
{
JButton btnCalc = new JButton("Donate"), btnLoad = new JButton("Load File"), btnExit = new JButton("Exit");
JLabel name, amount, intro = new JLabel("Would You Like to Donate to a Charity Today? It Only Takes a Few Moments"), message1 = new JLabel(""), message2 = new JLabel("");
JTextField textName, textAmount;
// Create String Array to list charities in the combobox
String[] charities = { "Choose a Charity or Enter a New Charity",
"American Foundation for Children with AIDS",
"American Red Cross",
"Breast Cancer Research Foundation",
"Livestrong *Formerly Lance Armstrong Foundation*",
"Michael J. Fox Foundation for Parkinson's Research" };
JComboBox charityList = new JComboBox(charities);
String file ="Charity.txt";
// Variables used later
double dAmount;
String Charity = null;
int debug = 0; // change to 1 to turn debug mode on
// Variables initialized for Database Stuff
Object[][] databaseInfo;
Object[] columns = {"name", "charity", "amount"};
Connection conn = null;
ResultSet rows;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String DBname = "charity";
String DBusername = "root";
String DBpass = "password";
// Variables and Class for TableModel
DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns){
public Class getColumnClass(int column) {
Class returnValue;
// Verifying that the column exists (index > 0 && index < number of columns
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
// Returns the class for the item in the column
returnValue = Object.class;
}
return returnValue;
}
};
/**
Sets the title, size and layout of the JFrame.<!-- -->Also calls the methods to setup the panels.
*/
public Charity()
{
super("Donations to Charities"); // Title of frame
setLayout(new FlowLayout()); // Declare layout of frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Default close
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get screen size
this.setResizable( false ); // turn off frame resize
this.setSize(600, dim.height-100); // set size of frame
CreatePanels();
GetAction(); // Call ActionListeners
CreateDatabase();
}
public void CreatePanels()
{
SetupCharityGroup(); // Call method to setup charity list panel
SetupDataPanel(); // Call method to setup data collection panel
SetupDisplayTable();
setVisible(true); // Make frame visible
}
/**
Method to setup the display panel containing a JTable that will show the information read from the database.
*/
private void SetupDisplayTable()
{
JTable table = new JTable(dTableModel); // Create a JTable using the custom DefaultTableModel
table.setFont(new Font("Serif", Font.PLAIN, 16)); // Increase the font size for the cells in the table
table.setRowHeight(table.getRowHeight()+5); // Increase the size of the cells to allow for bigger fonts
table.setAutoCreateRowSorter(true); // Allows the user to sort the data
// right justify amount column
TableColumn tc = table.getColumn("amount");
RightTableCellRenderer rightRenderer = new RightTableCellRenderer();
tc.setCellRenderer(rightRenderer);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Disable auto resizing
// Set the width for the columns
TableColumn col1 = table.getColumnModel().getColumn(0);
col1.setPreferredWidth(200);
TableColumn col2 = table.getColumnModel().getColumn(1);
col2.setPreferredWidth(275);
TableColumn col3 = table.getColumnModel().getColumn(2);
col3.setPreferredWidth(75);
// Put the table in a scrollpane and add scrollpane to the frame
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(552, 400));
this.add(scrollPane, BorderLayout.CENTER);
}
/**
Method to setup the data panel containing textFields, Labels, and buttons.
*/
private void SetupDataPanel()
{
JPanel pan = new JPanel();
GridLayout grid = new GridLayout(0, 1, 5, 5);
pan.setLayout(grid);
// Setup TextFields and Labels for name of person donating
// and add them to the panel
name = new JLabel("Name");
textName = new JTextField("", 16);
textName.setHorizontalAlignment(JTextField.RIGHT);
pan.add(name);
pan.add(textName);
// Setup TextFields and Labels for amount being donated
// and add them to the panel
amount = new JLabel("Donation Amount");
textAmount = new JTextField("", 4);
textAmount.setHorizontalAlignment(JTextField.RIGHT);
pan.add(amount);
pan.add(textAmount);
// add buttons and message labels to panel
pan.add(intro);
pan.add(btnCalc);
pan.add(btnLoad);
pan.add(btnExit);
pan.add(message1);
pan.add(message2);
this.add(pan);
}
/**
Method to setup the charity panel with a border containing an editable combobox filled with a list of charities.
*/
private void SetupCharityGroup()
{
JPanel Boxpan=new JPanel();
Boxpan.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Charities"));
this.add(Boxpan);
charityList.setEditable(true);
Boxpan.add(charityList);
}
/**
Add ActionHandlers to interactive elements.
*/
private void GetAction()
{
ActionHandler handler = new ActionHandler();
btnLoad.addActionListener(handler);
btnCalc.addActionListener(handler);
btnExit.addActionListener(handler);
charityList.addActionListener( handler );
}
/**
Method to make ActionHandlers into ActionListeners.
*/
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
String incmd = evt.getActionCommand();
if (incmd.equals("Donate")) // If Donate button is pressed
if (textName.getText().isEmpty())
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: Name of Donor missing!<font>");
} else
CheckDonate();
else if (incmd.equals("Load File")) // If Load File button is pressed
DatabaseLoad();
else if (incmd.equals("Exit")) // If Exit button is pressed
System.exit(0);
}
}
/**
Method to check if charity is selected in the combobox.<!-- -->If a charity is selected, call CharitySelected method, otherwise send error message to Frame.
*/
private void CheckCharity()
{
Object selectedCharity = charityList.getSelectedItem();
if (charityList.getSelectedIndex() == 0) // if charity is not selected
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: No Charity Selected!<font>");
} else CharityIsSelected();
}
/**
If charity is selected, set the selected value to "Charity" variable and call method to thank donator.
*/
private void CharityIsSelected()
{
Object selectedCharity = charityList.getSelectedItem();
Charity = selectedCharity.toString(); // selectedCharity Object converted to String
ThankYou();
}
/**
Thank the donator and call the databseAdd method.
*/
private void ThankYou()
{
message1.setText("Thank You! "+textName.getText());
message2.setText(" $"+textAmount.getText()+" Will be donated to "+Charity);
DatabaseAdd();
}
/**
Method that will check that donation amount is a number in a range between 1 and 1000000000.
*/
private void CheckDonate()
{ try
{
dAmount = Double.parseDouble(textAmount.getText());
if(dAmount <= 0.0 || dAmount > 1000000000 )
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount invalid</font>");
} else CheckCharity();
} catch (NumberFormatException ex) {
// Executes if the data entered is not a number
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount Not Recognized</font>");
}
}
}
public void DBConnection()
{ try
{
// The driver allows you to query the database with Java
// forName dynamically loads the class for you
Class.forName(driver);
// DriverManager is used to handle a set of JDBC drivers
// getConnection establishes a connection to the database
// You must also pass the userid and password for the database
conn = DriverManager.getConnection (url, DBusername, DBpass);
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
} catch (ClassNotFoundException ex) {
// Executes if the driver can't be found
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
message1.setText("Driver Error: contact admin");
message2.setText("");
}
}
/**
Method to add the entered information to the database.<!-- -->Once the information is added to the database, clear the form fields.
*/
private void DatabaseAdd()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// Prepare the query and values to be inserted into the database
String str="INSERT INTO donations(name,charity,amount) VALUES (?,?,?)";
java.sql.PreparedStatement statement = conn.prepareStatement(str);
statement.setString(1,textName.getText());
statement.setString(2,Charity);
statement.setDouble(3,dAmount);
statement.executeUpdate();
// Reset form after saved to database
textName.setText("");
textAmount.setText("");
charityList.setSelectedIndex(0);
s.close();
DatabaseLoad(); // Call the Database Info
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will load the database information and display it in Frame in a JTable.
*/
private void DatabaseLoad()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// This is the query I'm sending to the database
String selectStuff = "SELECT `name`, `charity`, `amount` FROM `"+DBname+"`.`donations` ";
// A ResultSet contains a table of data representing the
// results of the query. It can not be changed and can
// only be read in one direction
rows = s.executeQuery(selectStuff);
// Set the table RowCount to 0
dTableModel.setRowCount(0);
// Temporarily holds the row results
Object[] tempRow;
// next is used to iterate through the results of a query
while(rows.next())
{
// Gets the column values based on class type expected
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getDouble(3) };
dTableModel.addRow(tempRow); // Adds the row of data to the end of the model
}
// Successfully loaded, message the user
message1.setText("<html><font color='red'>Database Info Loaded</font>");
message2.setText("");
s.close();
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will create the database if it does not exist.
*/
private void CreateDatabase()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String dbCreate = "CREATE DATABASE "+DBname;
s.executeUpdate(dbCreate);
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
CreateTables();
}
/**
Method will create the table needed in the database.
*/
private void CreateTables()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String tableCreate = "create table "+DBname+".donations " + "(`name` varchar(200), " + "`charity` varchar(200), " + "amount double)";
s.executeUpdate(tableCreate);
// After creating the tables
// Load the information from the textfile
LoadTextFile();
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
}
public void LoadTextFile()
{
}
// To change justification to the right
class RightTableCellRenderer extends DefaultTableCellRenderer {
public RightTableCellRenderer() {
setHorizontalAlignment(JLabel.RIGHT);
}
}
// Main method calls the constructor
public static void main(String[] args)
{
new Charity();
}
}