不推荐使用构造函数csvreader(reader char)错误

时间:2018-05-15 03:31:32

标签: java csv opencsv reader

我想用servlet将文件CSV上传到MySQL,我有这样的代码,我的代码出错了。

package ServToDb;

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import com.opencsv.CSVReader;


import Connection.Database;

@WebServlet("/ImportCSVtoDB")
public class ImportCSVtoDB extends HttpServlet {
    private static final long serialVersionUID = 1L;       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImportCSVtoDB() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }


    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String target_file ;  // fileThatYouWantToFilter
        File folderToScan = new File("C:/Users/DELL/Music/"); //  this is the path we are scanning        
        File[] listOfFiles = folderToScan.listFiles();// this is the list of files returned in this folder       
        for (int j = 0; j < listOfFiles.length; j++) { // for each file in the folder
            if (listOfFiles[j].isFile()) {
                target_file = listOfFiles[j].getName();
                if (target_file.equals("blog.csv")) { // look for the file. You can also check if it ends with csv etc.              
            try 
            {
                Database db = new Database(); 
                String loadQuery = "LOAD DATA LOCAL INFILE 'C:/Users/DELL/Music/csvtest.csv' INTO TABLE" 
                        + "importcsv FIELDS TERMINATED BY ','LINES TERMINATED BY '\n' (fname, sex) "; //remember to change the path here as well
                Statement stmt = db.dbConn().createStatement();
                stmt.execute(loadQuery);                            
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }                   
            try (CSVReader reader = new CSVReader(new FileReader("C:/Users/DELL/Music/" + target_file), ',');)
            {
                Database db = new Database();
                String insertQuery = "Insert into importcsv (fname, sex) values (?,?)";//write your insertion query
                PreparedStatement pstmt = db.dbConn().prepareStatement(insertQuery);
                String[] rowData = null;// create empty array which will hold values from csv
                while((rowData = reader.readNext()) != null)
                {
                    int i = 0;
                    for (String data : rowData)
                        {
                        i++; 
                            if (i<3) {
                                pstmt.setString(i, data);
                                    if (i == 2) {
                                        pstmt.addBatch();// add batch
                                    }
                                    if (i % 30 == 0)// insert when the batch size is 10
                                        {
                                        pstmt.executeBatch(); // execute queries
                                        }
                            }
                        }
                }

            }
            catch (Exception e) {
                e.printStackTrace();}
                }
            }
        }
        out.println("success");
    }
}

但我得到这样的错误。

The constructor CSVReader(Reader, char) is deprecated

来自第60行

try (CSVReader reader = new CSVReader(new FileReader("C:/Users/DELL/Music/" + target_file), ',');)

如何运行此代码请帮助我,提前感谢您的帮助。我不打算为我做这件事,我只是被困住了,需要帮助找到我的路。

3 个答案:

答案 0 :(得分:2)

这里真正的答案是:

  • 您搜索的词语已弃用
  • 然后您会发现:已弃用表示某些方法已被标记,以便您 不再使用它(请参阅here
  • 请注意应该:您仍然可以使用它,但是该库的某些未来版本可能会删除那个ctor /方法,然后您的代码将无法编译任何更多(意思是:上面是警告,理论上你可以忽略它)
  • 但忽略是错误的做法。

相反:你转向你正在使用的类的javadoc(可能是here),找到:

  

已过时。请改用CSVReaderBuilder。

构建器类已记录在案here,包括一个用法示例。

除此之外:如果你真的遇到错误(就像你的IDE告诉你这是一个错误)那么那是因为你以一种警告<的方式配置你的IDE设置/ em>被标记为错误(所以这又是你可以轻易影响自己的东西)。

最后:这里真正的答案是不要放下你不理解的代码。看来你从某个地方获得了代码,并且你开始使用它,而没有做任何研究该代码正在做什么。这是一种效率低下的方法。您想要了解源代码中的每个和字符。如果你不理解某些东西,那么你研究,直到你明白它为止。这就是你学习编程的方法。

答案 1 :(得分:0)

这是不推荐使用的代码的确切解决方案:

CSVParser csvParser = new CSVParserBuilder().withSeparator(',').build();

CSVReader reader = new CSVReaderBuilder(new FileReader("C:/Users/DELL/Music/" + 
target_file)).withCSVParser(csvParser).build();

答案 2 :(得分:-2)

除非您专门尝试使用该CSV阅读器包,否则您可以使用扫描仪?

Scanner scanner = new Scanner("fileName.csv"); //open the file
while(scanner.hasNextLine()) { //Iterate through the file
    String line = scanner.nextLine(); //grab the next line
    String[] lineParts = line.split(","); //split based on commas and do something with the data
}
scanner.close(); //close the file