0

我有一个如下所示的文本文件:

人 1 姓名
人 1 年龄
人 1 地址

Person2 姓名
Person2 年龄
Person2 地址

Person3 姓名
Person2 年龄
Person3 地址

我需要将信息获取到数据库。

我有数据库连接,并且知道一旦将行放入正确的变量中,如何将信息输入数据库。. . 但是我如何让java识别每一行并将信息设置为一个变量。

基本上我需要获取文本文件信息并添加到以下变量

$姓名
$年龄
$地址

我想过使用数组,但由于我混合了字符串和数字,我不能使用字符串数组。

由于我每行使用 Line,因此没有分隔符。

**更新信息**

我使用姓名、年龄和地址作为示例变量,并且得到了一些有效的答案,但我仍然无法让它完全有效,所以我应该发布整个代码。. .

我也愿意进行代码清理(我真的是 Java 新手)

给出的答案让我有点工作,除了读者用空格分隔变量并且在名称和地址这样的情况下都有空格,空格分隔符没有给我我需要的结果。

这是文本文件的内容:

Ray Wade
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();
}
}
4

4 回答 4

0

使用 BufferedReader 一次读取一行,从该行中提取所需的信息并将其分配给变量。如果您想将它保存在内存中,请使用具有这 3 个属性的 POJO。

您可以使用正则表达式拆分行并获取所需的值。

于 2013-03-21T13:55:31.277 回答
0

我写了一组做类似事情的函数。我像其他用户建议的那样使用 bufferedReader。

public ArrayList<String> readFileToMemory(String filepath)
{
    BufferedReader br = null;
    String currentLine = null;
    ArrayList<String> fileContents = new ArrayList<String>();

    try
    {
        br = new BufferedReader(new FileReader(filepath));
        while((currentLine = br.readLine()) != null)
        {
            //fileContents.add(br.readLine());
            fileContents.add(currentLine);
        }

    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            br.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    return fileContents;
}

这只会将文件的每一行作为列表中的单独条目读取。只需输入条目并做您需要的事情。

于 2013-03-21T14:05:58.770 回答
0

以下代码片段将解决您的问题。

public class Test {
 public static void main( String[] args ) throws Exception
    {
        HashMap<String, Person> personMap = new HashMap<String, Person>();
        try
        {
            BufferedReader in = new BufferedReader( new FileReader( "File Path" ) );
            String str;
            Person person = new Person();
            int count = 0;
            String key = "";
            while( ( str = in.readLine() ) != null )
            {

                if ( null != str && str.trim().length() == 0 )
                {
                    personMap.put( key, person );
                    count = -1;
                    person = new Person();
                }
                else {
                    String arr[] = str.split( " " );
                    key = arr[0];
                    if (count == 0) {
                        person.setName( arr[1] );
                    }
                    else if (count == 1) {
                        person.setAge(  arr[1] );
                    }
                    else if (count == 2) {
                        person.setAddress(  arr[1] );
                    }
                }
                count ++;
            }
            personMap.put( key, person );
            in.close();
        }
        catch( IOException e )
        {
            System.out.println( "Exception" + e.getMessage() );
        }
    }
}

public class Person
{
    private String name    = null;

    private String age     = null;

    private String Address = null;

    public String getName()
    {
        return name;
    }

    public void setName( String name )
    {
        this.name = name;
    }

    public String getAge()
    {
        return age;
    }

    public void setAge( String age )
    {
        this.age = age;
    }

    public String getAddress()
    {
        return Address;
    }

    public void setAddress( String address )
    {
        Address = address;
    }

}

我希望它有帮助

于 2013-03-21T14:24:13.800 回答
0

如果您只这样做一次,只需在记事本 ++ 中进行 3 次替换

将 \r\n\r\n 替换为“|||” 将 \r\n 替换为 "," 替换 ||| 与 \r\n

那么你就有了一个常规的 .csv 文件。

于 2013-03-21T17:49:55.667 回答