problem upload text file

Posted on 2006-05-25
Last Modified: 2010-04-01
** i tried to use below code to upload the text delimiter file. if the first field or last field is missing it will be error.
eg. suppose have 1,2,3,4,5,6,7,8,9
if the text file don't have 1 or 9 it will have error. can i append a space "" on it? how?


      MultipartRequest parser = new ServletMultipartRequest(request,"C:\\abideetl\\xlsupload\\temp");

      String savedir = parser.getURLParameter("savedir");
      String savefname = parser.getURLParameter("savefname");

      File savedfile = parser.getFile("upload_file");

            response.sendRedirect("sgt_uploadinv.jsp?errmsg=No file or invalid file selected.");

            File destfile = new File("C:\\abideetl\\xlsupload\\" + savedir + "\\" + savefname);
            if ( destfile.exists() ) {
            if ( savedfile.renameTo(destfile) ) {
                  //objOut.println("File Uploaded Okay");
            } else {


            source = (DataSource)ctx.lookup("java:comp/env/jdbc/seagate");
            conn = source.getConnection();

            is = new FileInputStream(destfile);
            inputFile = new BufferedReader(new InputStreamReader(is));

            String line = "";
            boolean header=true;

            int[] arrlen = new int[]{30,20,20,8,4,2,2,20,8};

            // first, make sure SGT_POS_TMP is empty
            pstmt = conn.prepareStatement("delete from SGT_INV_TMP");

            strsql = "INSERT INTO SGT_INV_TMP VALUES (?,?,?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(strsql);

            // parse thru file line by line, then insert blindly into SGT_INV_TMP table
            while ((line = inputFile.readLine()) != null) {
                  if(header) { header=false; continue;}
                  if(line.trim().equals("")) continue;
                  StringTokenizer strtok = new StringTokenizer(line,"\t",true);
                  StringBuffer strval = new StringBuffer();

                  ArrayList emptylist = new ArrayList();
                  ArrayList paramlist = new ArrayList();


                        //int emptycount = 0;
                        boolean newEmpty = true;
                        int tokencount = 0;
                        String strempty = "";

                        String strtmp = "";
                        //String strprevtmp = "-1";

                              strtmp = AchUtil.getEscapedString(AchUtil.getNonNullString(strtok.nextToken()),"'","''").trim();

                              if(!newEmpty && !strtmp.equals("")){

                                    for(int n=0;n<emptylist.size();n++)
                                    newEmpty = true;
                              // this is to explicitly break the tokenizer in case the file has extra columns

                              if(tokencount==9 && newEmpty) {


                                    tokencount += 1;
                                    // get rid of encapsulating double quotes
                                    if((strtmp.indexOf("\"")==0) && (strtmp.lastIndexOf("\"")==(strtmp.length()-1))) {
                                          strtmp = strtmp.substring(1,strtmp.length()-1).trim();

                                    // first must check if previous token is empty, if yes then append

                                    if(tokencount==5){// || tokencount==23){

                                                paramlist.add(new Integer(df.parse(strtmp).intValue()));
                                                paramlist.add(new Integer(df2.parse(strtmp).intValue()));

                                    }else if(tokencount==4 || tokencount==9){

                                          // cut down to size if longer than column length
                                          if(arrlen[tokencount-1] >= strtmp.length()){


                                          }else {




                                          tokencount += 1;

                                                emptylist.add(new Integer(0));





                                          newEmpty = false;



                              newEmpty = true;

                  }catch(Exception ex){

                        errMsg = ex.getMessage();
                        errMsg += "sql="+strval.toString();


                  for(int n=0;n<paramlist.size();n++){

                  //int retval2 = stmt.executeUpdate(strsql);
                  int retval2 = pstmt.executeUpdate();
                  if(retval2 > 0) { //good
                        commit = true;
                        commit = false;
                  //if(pstmt!=null) pstmt.close();

            }//end while

            if(commit) {
            } else {


}catch( ioe){
      //out.println("IO Exception :"+ioe.getMessage());
      errMsg = ioe.getMessage();

}catch(java.sql.SQLException sqle){
      commit = false;
  if(conn!=null) conn.rollback();
      //out.println("SQL Exception :"+sqle.getMessage());
      errMsg = sqle.getMessage();

}catch(Exception e){
      commit = false;
      //out.println("Exception :"+e.getMessage());
      errMsg = e.getMessage();


      //if(stmt!=null) stmt.close();errMsg += " statement closed.";
      if(pstmt!=null) pstmt.close();errMsg += " statement closed.";
      if(conn!=null) conn.close();errMsg += " connection closed.";
      if(inputFile!=null) inputFile.close();
      if(is!=null) is.close();
Question by:mayachoy
    1 Comment
    LVL 16

    Accepted Solution

    Check out this API.  It can deal with situations like this.  There is a boolean you can pass on the constructor to have it pad out missing columns in the file:


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Better Security Awareness With Threat Intelligence

    See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

    The recent Microsoft changes on update philosophy for Windows pre-10 and their impact on existing WSUS implementations.
    Great sound, comfort and fit, excellent build quality, versatility, compatibility. These are just some of the many reasons for choosing a headset from Sennheiser.
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now