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

x
?
Solved

problem upload text file

Posted on 2006-05-25
3
Medium Priority
?
186 Views
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?

try{

      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");

      if(savedfile==null){
            response.sendRedirect("sgt_uploadinv.jsp?errmsg=No file or invalid file selected.");
      }else{


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

            }


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


            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");
            pstmt.execute();
            pstmt.close();

            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();

                  try{

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

                        String strtmp = "";
                        //String strprevtmp = "-1";
                        while(strtok.hasMoreTokens()){

                              strtmp = AchUtil.getEscapedString(AchUtil.getNonNullString(strtok.nextToken()),"'","''").trim();
                              //out.println("("+strtmp+")");

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

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

                              if(tokencount==9 && newEmpty) {

                                    break;
                              }


                              if(!strtmp.equals("")){
                                    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){

                                          if(strtmp.indexOf("(")!=-1){
                                                paramlist.add(new Integer(df.parse(strtmp).intValue()));
                                                //out.println("<br>"+tokencount+"_"+df.parse(strtmp).intValue());
                                          }else{
                                                paramlist.add(new Integer(df2.parse(strtmp).intValue()));
                                                //out.println("<br>"+tokencount+"_"+df2.parse(strtmp).intValue());
                                          }

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

                                          paramlist.add(strtmp);
                                          //out.println("<br>"+tokencount+"_"+strtmp);
                                    }else{
                                          // cut down to size if longer than column length
                                          if(arrlen[tokencount-1] >= strtmp.length()){

                                                paramlist.add(strtmp);
                                                //out.println("<br>"+tokencount+"_"+strtmp);

                                          }else {

                                                paramlist.add(strtmp.substring(0,arrlen[tokencount-1]));
                                                //out.println("<br>"+tokencount+"_"+strtmp.substring(0,arrlen[tokencount-1]));
                                          }
                                    }

                              }else{


                                    if(!newEmpty){

                                          tokencount += 1;
                                          if(tokencount==5){

                                                emptylist.add(new Integer(0));
                                                //out.println("<br>"+tokencount+"0");

                                          }else{

                                                emptylist.add("");
                                                //out.println("<br>"+tokencount);

                                          }

                                    }else{

                                          newEmpty = false;
                                    }


                              }

                        }//
                        if(!newEmpty){
                              strval.append(strempty);

                              newEmpty = true;
                        }


                  }catch(Exception ex){

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

                        break;
                  }



                  for(int n=0;n<paramlist.size();n++){
                        pstmt.setObject((n+1),paramlist.get(n));
                        //out.println((n+1)+"="+paramlist.get(n));
                  }



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



            }//end while

            
            
            if(commit) {
                  conn.commit();
            } else {
                  conn.rollback();
            }


      }


}catch(java.io.IOException ioe){
      commit=false;
      //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();

}finally{

      //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();
}
0
Comment
Question by:mayachoy
1 Comment
 
LVL 16

Accepted Solution

by:
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:

http://www.sourceforge.net/projects/pzfilereader


Joe
0

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