gpt4 book ai didi

java - 无法从mysql数据库中找到java中的csv文件

转载 作者:行者123 更新时间:2023-11-30 22:13:41 25 4
gpt4 key购买 nike

我开发了一个 Java 程序来将数据从 CSV 加载到 MySQL,但在其中我无法从给定路径找到 CSV 文件,并且出现错误 FileNotFoundException。我已经添加了程序的代码和日志文件

public class Csvfile {

public static void main(String[] args) throws Exception{
/* Create Connection objects */
Class.forName ("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/csv","root","admin");
PreparedStatement sql_statement = null;
String jdbc_insert_sql = "insert into csvdata"+"(id,age)values"+"(?,?)";

sql_statement = conn.prepareStatement(jdbc_insert_sql);
/* Read CSV file in OpenCSV */
String inputCSVFile = "data1.csv";
CSVReader reader = new CSVReader(new FileReader(inputCSVFile));
/* Variables to loop through the CSV File */
String [] nextLine; /* for every line in the file */
int lnNum = 0; /* line number */

while ((nextLine = reader.readNext()) != null) {
lnNum++;
/* Bind CSV file input to table columns */
sql_statement.setString(1, nextLine[0]);
/* Bind Age as double */
/* Need to convert string to double here */
sql_statement.setDouble(2,Double.parseDouble(nextLine[1]));
/* execute the insert statement */
sql_statement.executeUpdate();
}
/* Close prepared statement */
sql_statement.close();
/* COMMIT transaction */
conn.commit();
/* Close connection */
conn.close();

}
;

日志文件

Exception in thread "main" java.io.FileNotFoundException: data1.csv (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at csvfile.Csvfile.main(Csvfile.java:32)

最佳答案

我通过添加csv文件的路径找到了答案

  sql_statement = conn.prepareStatement(jdbc_insert_sql);
/* Read CSV file in OpenCSV */
String inputCSVFile = "R:\\java task\\22-8-16\\Csvfile\\src\\csvfile\\data1.csv";
CSVReader reader = new CSVReader(new FileReader(inputCSVFile));

添加路径后一切正常

关于java - 无法从mysql数据库中找到java中的csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39200007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com