[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now


problem upload text file

Posted on 2006-05-25
Medium Priority
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(java.io.IOException 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

Joe earned 1000 total points
ID: 16768213
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:



Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

LinkedIn blogging is great for networking, building up an audience, and expanding your influence as well. However, if you want to achieve these results, you need to work really hard to make your post worth liking and sharing. Here are 4 tips that ca…
MSSQL DB-maintenance also needs implementation of multiple activities. However, unprecedented errors can hamper the database management. In that case, deploying Stellar SQL Database Toolkit ensures fast and accurate database and backup repair as wel…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses
Course of the Month19 days, 21 hours left to enroll

872 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