【问题标题】:relative path not working in java swing相对路径在java swing中不起作用
【发布时间】:2014-05-13 15:49:16
【问题描述】:

所以当给定访问数据库的绝对路径时,这个 swing 程序运行良好。但是当我尝试使用相对路径访问数据库时,程序不会运行。我将 MS Access 数据库保存在 Eclipse 的 src 文件夹中。那么我应该如何纠正呢?

    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;


    public class r_search_1 extends JFrame implements ActionListener {

        JFrame frame1;
        JLabel l0, l1, l2;
        JComboBox c1;
        JButton b1;
        Connection con;
        ResultSet rs, rs1;
        Statement st, st1;
        PreparedStatement pst;
        String ids;
        static JTable table;
        String[] columnNames = {"SECTION NAME", "REPORT NAME", "CONTACT", "LINK"};
        String from;

          Vector v = new Vector();

        r_search_1() {

            l0 = new JLabel("Fetching Search Results...");
            l0.setForeground(Color.blue);
            l0.setFont(new Font("Serif", Font.BOLD, 20));
            l1 = new JLabel("Search");
            b1 = new JButton("submit");
            l0.setBounds(100, 50, 350, 40);
            l1.setBounds(75, 110, 75, 20);
            b1.setBounds(150, 150, 150, 20);
            b1.addActionListener(this);

            setTitle("Search Executive Reports :) ");
            setLayout(null);
            //setVisible(true);
            setSize(500, 500);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

            add(l0);
            add(l1);;
            add(b1);
            try {

                File dbFile = new File("executive_db.accdb");
                String path = dbFile.getAbsolutePath();
                Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
                //String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ= " + path;

                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                st = con.createStatement();
                rs = st.executeQuery("select index_name from Index1");

                while (rs.next()) {
                    ids = rs.getString(1);
                    v.add(ids);

                }
                c1 = new JComboBox(v);
                c1.setEditable(true);c1.setSelectedItem("");

                c1.setBounds(150, 110, 150, 20);

                add(c1);
                st.close();
                rs.close();
            } catch (Exception e) {
            }
            setVisible(true);
        }

        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == b1) {
                showTableData();
            }

        }

        public void showTableData() {

            frame1 = new JFrame("Database Search Result");
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame1.setLayout(new BorderLayout());
    //TableModel tm = new TableModel();
            DefaultTableModel model = new DefaultTableModel();
            model.setColumnIdentifiers(columnNames);
    //DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
    //table = new JTable(model);
            table = new JTable();
            table.setModel(model);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            table.setFillsViewportHeight(true);
            JScrollPane scroll = new JScrollPane(table);
            scroll.setHorizontalScrollBarPolicy(
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scroll.setVerticalScrollBarPolicy(
                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            from = (String) c1.getSelectedItem();

            String uname = "";
            String email = "";
            String pass = "";
            String cou = "";

            try {

                 pst = con.prepareStatement("select distinct Section.Section_Name,Report.Report_Name,Report.Link,Contact.Contact_Name "
                            + "FROM (( Section INNER JOIN Report ON Report.Section_ID=Section.Section_ID ) INNER JOIN Contact ON Contact.Contact_ID=Report.Contact_ID )  LEFT JOIN Metrics ON Metrics.Report_ID=Report.Report_ID  "
                            + " WHERE Section.Section_Name LIKE '%"+from+"%' OR Report.Report_Name LIKE '%"+from+"%' OR Metrics.Metric_Name LIKE '%"+from+"%' OR Contact.Contact_Name LIKE '%"+from+"%' ");
                ResultSet rs = pst.executeQuery();
                int i = 0;
                while (rs.next()) {
                    uname = rs.getString("Section_Name");
                    email = rs.getString("Report_Name");
                    pass = rs.getString("Contact_Name");
                    cou = rs.getString("Link");
                    model.addRow(new Object[]{uname, email, pass, cou});
                    i++;
                }
                if (i < 1) {
                    JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
                }
                if (i == 1) {
                    System.out.println(i + " Record Found");
                } else {
                    System.out.println(i + " Records Found");
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
            frame1.add(scroll);
            frame1.setVisible(true);
            frame1.setSize(1000, 400);
        }

        public static void main(String args[]) {
            new r_search_1();
        }
    }

【问题讨论】:

    标签: java eclipse swing ms-access relative-path


    【解决方案1】:

    默认情况下,Eclipse Java 项目以工作目录作为项目的根目录运行 Java。因此,相对文件new File("executive_db.accdb") 直接引用项目中的文件,而(根据它的声音)您已将文件放在“src”目录中。

    因此,您的选择是:

    • 将相关文件定义更改为new File("src/executive_db.accdb")
    • 通过更改运行配置来更改 Java 的工作目录。这可以通过选择 Run -> Run Configurations、导航到您的运行配置并更改“参数”选项卡中的“工作目录”值来执行。

    【讨论】:

      【解决方案2】:

      如果您将文件放在 eclipse 项目文件夹而不是源文件夹中,您可以直接访问它

      File dbFile = new File("executive_db.accdb");
      

      默认情况下,如果您将文件放在 src 文件夹中,eclipse 会在编译时将其复制到类文件夹中并且可以访问。如果不是这种情况,您可以将文件复制到类文件夹并使用ClassLoader 获取路径。

      URL url = ClassLoader.getSystemResource("executive_db.accdb");
      File dbFile = new File(url.getPath());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-12
        • 2013-10-22
        • 1970-01-01
        • 2013-02-19
        • 2015-08-30
        • 2011-03-17
        • 2014-06-25
        • 2018-09-15
        相关资源
        最近更新 更多