在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();
}
# 1 楼答案
当保存到数据库时,反斜杠会从路径中丢失,因为字符串直接插入到
PreparedStatement
中,而不是设置为参数。改为这样做: