我想将数据从 .txt 文件(位于项目文件夹中)加载到 mySQL 表中。
String path = getClass().getResource("/DataEmployees.txt").getPath();
String query = "LOAD DATA LOCAL INFILE ? INTO TABLE employees LINES TERMINATED BY '\r\n' STARTING BY 'xxx';";
try( Connection connection = Main.dataSource.getConnection() ){
try( PreparedStatement preparedStatement = connection.prepareStatement(query) ){
preparedStatement.setString(1, path);
preparedStatement.executeUpdate();
}
}catch(Exception exception){
ExceptionDialog exceptionDialog = new ExceptionDialog("Couldn't load default sample data",exception);
exceptionDialog.showAndWait();
};
但是我收到一个错误:
java.sql.SQLException: Unable to open file '/C:/Users/Tomek/EclipseWorkspace/Pizza%20Service/bin/DataEmployees.txt'for 'LOAD DATA LOCAL INFILE' command.Due to underlying IOException:
** BEGIN NESTED EXCEPTION **
java.io.FileNotFoundException
MESSAGE: C:\Users\Tomek\EclipseWorkspace\Pizza%20Service\bin\DataEmployees.txt (The system cannot find the path specified)
STACKTRACE:
java.io.FileNotFoundException: C:\Users\Tomek\EclipseWorkspace\Pizza%20Service\bin\DataEmployees.txt (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at com.mysql.jdbc.MysqlIO.sendFileToServer(MysqlIO.java:3674)
at com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:2995)
at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:2245)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2638)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2535)
at
DataEmployees
位于另一个源文件夹中。
我不知道这里出了什么问题以及如何修复它。当我使用绝对路径时它有效:
字符串路径 =“C:/Users/Tomek/EclipseWorkspace/Pizza Service/files/DataEmployees.txt”;
编辑
String path="";
try {
path = getClass().getResource("/DataEmployees.txt").toURI().getPath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String query = "LOAD DATA LOCAL INFILE ? INTO TABLE employees LINES TERMINATED BY '\r\n' STARTING BY 'xxx';";
这有效,但在 eclipse 内。如果我将 jar 文件导出到桌面,则会出现异常:
java.sql.SQLException: Unable to open file 'null'for 'LOAD DATA LOCAL INFILE' command.Due to underlying IOException:
** BEGIN NESTED EXCEPTION **
java.io.FileNotFoundException
MESSAGE: null (The system cannot find the file specified)
STACKTRACE:
java.io.FileNotFoundException: null (The system cannot find the file specified)
最佳答案
如果您想从 jar 中读取该文件,请使用:
InputStream input = getClass().getResourceAsStream("/path/to/file");
路径以“/”开头,但这不是文件系统中的路径,而是类路径(内部 jar)中的路径。因此,如果您的文件名为 data.txt
并且位于 jar 文件根目录下的 files 文件夹中,您应该使用 getResourceAsStream("/files/data.txt")
来读取它作为流。
关于java - 如何将 .jar 内的文件中的数据加载到 Mysql 表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29604203/