有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中打开文件时出错

我用Java开发了一个系统。我可以保存pdf、文档等文件,它们保存在jTable。我想通过单击Jtable行打开这些文件。如果我试图打开本地磁盘中保存的文件,它们将无法打开。但我可以打开可移动磁盘上的文件。请帮我解决这个问题

这是我的代码:

 int row = jTable1.getSelectedRow();


        try {
        String value = (jTable1.getModel().getValueAt(row, 2).toString());

            //  Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler" + value);
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + value);


        } catch (Exception e) {
            e.printStackTrace();

        }

打开文件并获取目录路径:

try {

    JFileChooser chooser = new JFileChooser();

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.showOpenDialog(null);
    File selectedPfile = chooser.getSelectedFile();
    jTextField1.setText(selectedPfile.getAbsolutePath());


} catch (Exception e) {
    e.printStackTrace();
}

保存代码:

try {

            Connection con = DB.connect();

            PreparedStatement p = con.prepareStatement("insert into documents values( '" + jTextField3.getText() + "','" + jTextField2.getText() + "', '" + jTextField1.getText() + "')");

            p.executeUpdate();
            p.close();

            JOptionPane.showMessageDialog(null, "save success");


        } catch (Exception e) {
            e.printStackTrace();

        }

保存在数据库中的路径 enter image description here


共 (1) 个答案

  1. # 1 楼答案

    当保存到数据库时,反斜杠会从路径中丢失,因为字符串直接插入到PreparedStatement中,而不是设置为参数。改为这样做:

    try (Connection con = DB.connect()) {
        try (PreparedStatement p = con.prepareStatement(
                "insert into documents values (?, ?, ?)")) {
            p.setString(1, jTextField3.getText());
            p.setString(2, jTextField2.getText());
            p.setString(3, jTextField1.getText());
            p.executeUpdate();
        }
    } catch (SQLException e) {
        // handle exception...
    }