获取文件csv上传并添加mysql

时间:2017-08-20 21:24:52

标签: java mysql eclipse csv

我使用strust1将程序上传文件csv写入服务器。我上传文件到文件夹但是上传时我无法从文件csv中读取数据。我想从csv读取数据并写入mysql,但不成功。

文件上传:

@Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        StudentDAO student = new StudentDAO();
        List<Student> actorList = new ArrayList<>();
        FileUploadForm fileUploadForm = (FileUploadForm)form;

        FormFile file = fileUploadForm.getFile();

        //Get the servers upload directory real path name
        String filePath =
               getServlet().getServletContext().getRealPath("/") +"upload";

        //create the upload folder if not exists
        File folder = new File(filePath);
        if(!folder.exists()){
            folder.mkdir();
        }

        String fileName = file.getFileName();

        if(!("").equals(fileName)){

            System.out.println("Server path:" +filePath);
            File newFile = new File(filePath, fileName);

            if(!newFile.exists()){
              FileOutputStream fos = new FileOutputStream(newFile);
              fos.write(file.getFileData());
              fos.flush();
              fos.close();
              InsertData(newFile.getAbsoluteFile().toString());
            }


        }

private void InsertData(String pathFile){
    StudentDAO student = new StudentDAO();
    BufferedReader br = null;
    String path="";

    String line = "";
    String cvsSplitBy = ",";
    DB.OpenConnect();

        String query = "LOAD DATA LOCAL INFILE '" + pathFile + "' INTO TABLE student FIELDS ENCLOSED BY '\"' TERMINATED BY ';' ESCAPED BY '\"'\r\n" + 
                "LINES TERMINATED BY '\\r\\n';";
        try {
            DB.exeUpdate(query);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

但是当我运行它时出错。

java.sql.SQLException: Unable to open file 'E:Ebook tin hocJava.metadata.pluginsorg.eclipse.wst.server.core mp5wtpwebappsFileUploadFinalupload3.csv'for 'LOAD DATA LOCAL INFILE' command.Due to underlying IOException: 

** BEGIN NESTED EXCEPTION ** 

java.io.FileNotFoundException
MESSAGE: E:Ebook tin hocJava.metadata.pluginsorg.eclipse.wst.server.core    mp5wtpwebappsFileUploadFinalupload3.csv (The filename, directory name, or volume label syntax is incorrect)

STACKTRACE:

java.io.FileNotFoundException: E:Ebook tin hocJava.metadata.pluginsorg.eclipse.wst.server.core  mp5wtpwebappsFileUploadFinalupload3.csv (The filename, directory name, or volume label syntax is incorrect)
    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:3421)
    at com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:2617)
    at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:1788)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2209)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2619)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1709)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1628)
    at dao.DB.exeUpdate(DB.java:56)
    at action.FileUploadAction.InsertData(FileUploadAction.java:100)
    at action.FileUploadAction.execute(FileUploadAction.java:62)
    at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
    at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
    at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
    at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
    at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)


** END NESTED EXCEPTION **

文件夹我上传文件: E:\ Ebooktinhoc \ Java.metadata.plugins \ org.eclipse.wst.server.core \ TMP5 \ wtpwebapps \ FileUploadFinal \上传* .csv格式。 但错误:E:Ebook tin hocJava.metadata.pluginsorg.eclipse.wst.server.core mp5wtpwebappsFileUploadFinalupload3.csv。

为什么eclipse无法找到正确的路径?如何读取csv数据并将其导入mysql? 更新: 我的问题解决了。我使用命令sql:  "String sql = "insert into student values('" + tr[0] + "', '" + tr[1] + "', '" + tr[2] + "', '"+tr[3]+ "', '"+tr[4]+"')";并使用以下方法:

BufferedReader br = null;
 String path="";
 String cvsSplitBy = ",";
    try {
            br = new BufferedReader(new FileReader(pathFile));
            String line = br.readLine();
            while ((line = br.readLine()) != null) {                
                // use comma as separator
                String[] tr = line.split(cvsSplitBy);
                student.insertStudent(tr);
            }

它对我有用。三江源。

1 个答案:

答案 0 :(得分:0)

你使用&#34; multipart / form-data&#34; HTML表格上的标签?

我猜您的推荐网站是Struts file upload example