0

I am uploading a text file using servlets and reading it, and trying to insert into database

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        ServletContext context = getServletContext();
        String path = context.getRealPath(file);
        File file = new File(path);
        FileInputStream in = null;
        try {
            in = new FileInputStream(uploadFilePath+File.separator+file.getName());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                System.out.println(strLine);
                decodeAisData(strLine); //it is reading each line but not inserting into database
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

In the decode i have written the database insertion logic, but it is not executing

spt
  • 421
  • 4
  • 12
  • 27

1 Answers1

1

Looks like path of file is incorrect while reading, did you try
in = new FileInputStream(uploadFilePath + File.separator+file1.getName()); ? or better get the stream from Classloader using getResourceAsStream(), more information can be found in here

Community
  • 1
  • 1
user1339772
  • 783
  • 5
  • 19
  • Try using getServletContext().getResourceAsStream(), details information is provided here -http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream – user1339772 Nov 15 '13 at 14:56
  • Where are you getting Null Pointer? Your stack trace should provide you enough information to locate exact line – user1339772 Nov 15 '13 at 15:40
  • java.lang.NullPointerException atcom.journaldev.servlet.FileUploadServlet.doGet(FileUploadServlet.java:112) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) – spt Nov 15 '13 at 15:55
  • What is line 112 in FileUploadServlet.java ? – user1339772 Nov 15 '13 at 15:56
  • in.close(); i kept is.close(); – spt Nov 15 '13 at 16:21
  • if you are getting NPE at in.close() then looks like the NPE is thrown at in = new FileInputStream(file1.getName()) line due to which in variable never gets initialized and throws NPE at finally block – user1339772 Nov 15 '13 at 18:38
  • I have initialized the variable in with null value – spt Nov 16 '13 at 05:42
  • If its printing each line but not inserting in DB, then looks like there is a bug in decodeAisData() method. – user1339772 Nov 18 '13 at 15:10