2016-08-29 28 views
1

我開發了一個Java程序來將數據從CSV加載到MySQL,其中我找不到給定路徑中的CSV文件,並且出現錯誤FileNotFoundException。我添加的代碼和無法從mysql數據庫中找到java中的csv文件

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) 
+1

你的'data1.csv'文件位於哪裏?嘗試給絕對路徑。 – ma3stro

回答

0

我找到了答案通過添加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)); 

的路徑添加後,程序的日誌文件路徑工作正常