Write file in servlet

Hi all,
I am developing an application but there is a error in my code i culdnt find so far. Can anyone help?
I want to write to a .xml file in web server with servlet from remote. My code is
private static String message = "Error during Servlet processing";
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//        response.setContentType("text/html;charset=UTF-8");
        try {
            int len = request.getContentLength();
            byte[] input = new byte[len];
            ServletInputStream sin = request.getInputStream();
            int c, count = 0;
            while ((c = sin.read(input, count, input.length - count)) != -1) {
                count += c;
            sin.close();
            String inString = new String(input);
            int index = inString.indexOf("/n");
            if (index == -1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print(message);
                response.getWriter().close();
                return;
            String user = inString.substring(0, index);
            String data = inString.substring(index + 2);
            //decode application/x-www-form-urlencoded string
//            String decodedUser = URLDecoder.decode(user, "UTF-8");
//            String decodedData = URLDecoder.decode(data, "UTF-8");
//            int i = decodedData.indexOf("/n");
//            String user = decodedData.substring(0, i);
//            String db = decodedData.substring(i + 2, decodedData.length());
            String result = "no";
//            response.setContentType("text/html");
            String filename = "/WEB-INF/" + user + ".xml";
//            String pathName = getServletContext (  ) .getRealPath ( "/" + filename ) ;
//            String contentType = getServletContext (  ) .getMimeType ( pathName ) ;
//            if  ( contentType != null ) 
//                response.setContentType ( contentType ) ;
//            else
//                response.setContentType ( "application/octet-stream" ) ;
            try {
                OutputStream fcheck = null;
                byte[] buf = data.getBytes();
                fcheck = new FileOutputStream(filename);
                for (int i = 0; i < buf.length; i++) {
                    fcheck.write(buf);
result = "yes";
} catch (IOException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
result = "no";
// ServletContext context = getServletContext();
// set the response code and write the response data
response.setStatus(HttpServletResponse.SC_OK);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(result);
writer.flush();
writer.close();
} catch (IOException e) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(e.getMessage());
response.getWriter().close();
} catch (IOException ioe) {
ý am sending data from remote as a string and want to write it in xml. But it is not working. Where am i wrong?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

I fixed it. But now it doesnt write to file and there is no error. So i cant find where am a wrong.
I send a request, it is taking string but it is not writing to file eventhough it is entering the try block.
Why it isnt writing? Is not servlet let it to write to file. My working code is here
private static String message = "Error during Servlet processing";
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            int len = request.getContentLength();
            byte[] input = new byte[len];
            ServletInputStream sin = request.getInputStream();
            int c, count = 0;
            while ((c = sin.read(input, count, input.length - count)) != -1) {
                count += c;
            sin.close();
            String inString = new String(input);
            int index = inString.indexOf("/n");
            if (index == -1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print(message);
                response.getWriter().close();
                return;
            String user = inString.substring(0, index);
            String data = inString.substring(index + 2);
            //decode application/x-www-form-urlencoded string
//            String decodedUser = URLDecoder.decode(user, "UTF-8");
            String decodedData = URLDecoder.decode(data, "UTF-8");
//            int i = decodedData.indexOf("/n");
//            String user = decodedData.substring(0, i);
//            String db = decodedData.substring(i + 2, decodedData.length());
            String result = "no";
            String filename = user + ".xml";
            try {
                OutputStream fcheck = null;
                byte[] buf = decodedData.getBytes();
                fcheck = new FileOutputStream(filename);
                for (int i = 0; i < buf.length; i++) {
                    fcheck.write(buf);
// char buffer[]=new char[data.length()];
// data.getChars(0, data.length(), buffer, 0);
// FileWriter f0=new FileWriter(filename);
// for(int i=0;i<buffer.length;i++){
// f0.write(buffer[i]);
result = "yes";
} catch (IOException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
result = "no";
// ServletContext context = getServletContext();
// set the response code and write the response data
response.setStatus(HttpServletResponse.SC_OK);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(result);
writer.flush();
writer.close();
} catch (IOException e) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(e.getMessage());
response.getWriter().close();
} catch (IOException ioe) {

Similar Messages

  • How to write file to server side?

    hello,
    Could anyone pls help me...
    I just want to see an example how can I write to a file that is placed at the server(save place as the applet).
    p.s. I have been successfully read a file from there...
    Suppose I have signed the applet (self-signed), anymore security problem I need to pay attention to?
    Thanks a lot!!

    hi mandy, from the applet u can send the file to be written into the server to a servlet running in server and the servlet can in turn write the file into the servlet. by applet - servlet communication, u can easily read and write files to the server.

  • HELP! File Upload Servlet and Internet Explorer

    Hello people. I hope this is an easy problem to solve...
    I have a servlet upload program that works using Mozilla browser (www.mozilla.org), but for some reason it doesn't work using Microsoft IE. The servlet is also using the servlet upload API from Apache (commons).
    I'm using IE version 6.0.2800.1106 in a Win98SE host computer. I get a cannot find path specified error message (see below). At work, I also get the same error message using IE, but don't know what version. The OS is XP. Unfortunately, at work, I can't install Mozilla browser (or any software-company policy) to see if Mozilla works there too. I would've like to have tested to see if the upload program worked on Mozilla on a truly remote computer.
    So I figured, it must be a IE configuration issue, but darn it!! I began by resetting IE to default settings, but still have the problem, I played around with several different combinations of settings in "Tools"-->"Internet Options...", and I still get the error message. Someone PLEASE HELP ME!!!
    Dunno, if it will help, I've also pasted the upload servlet source code below and the html file that's calling the upload servlet, but you still need the Apache commons file upload API.
    Trust me on this one folks, for some reason it works for Mozilla, but not for IE. With IE, I can at least access web server, and therefore, the html file that calls the upload servlet , so I don't think it's a Tomcat configuration issue (version 5.0). I actually got the code for the file upload servlet from a book relatively new in the market (printed in 2003), and it didn't mention any limitations as far as what browser to use or any browser configuration requirements. I have e-mailed the authors, but they probably get a ton of e-mails...
    Anyone suggestions?
    Meanwhile, I will try to install other free browsers and see if the file upload program works for them too.
    ERROR MESSAGE:
    "HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: C:\TOMCAT\webapps\MyWebApps\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:43)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    root cause
    java.io.FileNotFoundException: C:\TOMCAT\webapps\MyWebApp\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         java.io.FileOutputStream.open(Native Method)
         java.io.FileOutputStream.(FileOutputStream.java:176)
         java.io.FileOutputStream.(FileOutputStream.java:131)
         org.apache.commons.fileupload.DefaultFileItem.write(DefaultFileItem.java:392)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:36)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    note The full stack trace of the root cause is available in the Tomcat logs.
    Apache Tomcat 5.0.16"
    FILE UPLOAD SERVLET source code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.commons.fileupload.*;
    import java.util.*;
    public class FileUploadCommons extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.print("File upload success. <a href=\"/MyWebApp/files/");
    out.print("\">Click here to browse through all uploaded ");
    out.println("files.</a><br>");
    ServletContext sc = getServletContext();
    String path = sc.getRealPath("/files");
    org.apache.commons.fileupload.DiskFileUpload fu = new
    org.apache.commons.fileupload.DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setRepositoryPath(path);
    try {
    List l = fu.parseRequest(request);
    Iterator i = l.iterator();
    while (i.hasNext()) {
    FileItem fi = (FileItem)i.next();
    fi.write(new File(path, fi.getName()));
    catch (Exception e) {
    throw new ServletException(e);
    out.println("</html>");
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    doPost(request, response);
    HTML PAGE that calls the upload servlet:
    <html>
    <head>
    <title>Example HTML Form</title>
    </head>
    <body>
    <p>Select a file to upload or browse
    currently uploaded files.</p>
    <form action="http://##.##.##.####/MyWebApp/FileUploadCommons"
    method="post" enctype="multipart/form-data">
    File: <input type="file" name="file"><br>
    <input value="Upload File" type="submit">
    </form>
    </body>
    </html>
    Thanks in advance for any assistance.
    -Dan

    I'm guessing what is happening is that Mozilla tells the servlet "here comes the file myfile.zip". The servlet builds a file name for it:
        String path = sc.getRealPath("/files");
        // path is now C:\TOMCAT\webapps\MyWebApps\files\
        fi.write(new File(path, fi.getName()));
        // append myfile.zip to "path", making it C:\TOMCAT\webapps\MyWebApps\files\myfile.zipIE, however, tells "here comes the file C:\WINDOWS\Desktop\myfile.zip". Now imagine what the path+filename ends up being...
    So what you want to do is something along the lines of (assuming Windoze):
    public static String basename(String filename)
        int slash = filename.lastIndexOf("\\");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // I think Windows doesn't like /'s either
        int slash = filename.lastIndexOf("/");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // In case the name is C:foo.txt
        int slash = filename.lastIndexOf(":");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        return filename;
        fi.write(new File(path, basename(fi.getName()));
        ....You can make the file name check more bomb proof if security is an issue. Long file names trying to overflow something in the OS, NUL characters, Unicode, forbidden names in Windos (con, nul, ...), missing file name, ...

  • Problem in downloading file using servlet

    Hello,
    I wnat to send a file throung servlet to my desktop program. when i call this servlet through internet explore it is working fine but when i call this in my desktop program then desktop program get nothing. my desktop program does not get anything. please help me. here is my both code servlet and desktop program.
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
              response.setContentType("text/html");
         //     PrintWriter out = response.getWriter();
              File filename = new File("");
    //          Set the headers.
              response.setContentType("application/x-download");
              response.setHeader("Content-Disposition", "attachment; filename=" + filename);
    //          Send the file.
              OutputStream out = res.getOutputStream( );
              returnFile(filename, out); // Shown earlier in the chapter
              String filePath = getServletContext().getRealPath("/");
              response.setContentType("application/x-download");
              response.setHeader("Content-Disposition", "attachment; filename="+"amit.doc");
         //     File tosave = new File(getServletContext().getRealPath("), cfile.getName());" +
              try{
              File uFile= new File(filePath);
              int fSize=(int)uFile.length();
              FileInputStream fis = new FileInputStream(uFile);
              PrintWriter pw = response.getWriter();
              int c=-1;
    //          Loop to read and write bytes.
    //          pw.print("Test");
              while ((c = fis.read()) != -1){
              pw.print((char)c);
    //          Close output and input resources.
              fis.close();
              pw.flush();
              pw=null;
              }catch(Exception e){
    public class AdDesktopClient {
         * @param args
         public static void main(String[] args) {
              try{ 
              URL url = new URL("http://localhost:8080/WebRoot1/servlet/Download");
              //URLEncoder.encode(xmlString);
              URLConnection connection = url.openConnection();
              HttpURLConnection con = (HttpURLConnection)connection;
              con.setDoInput(true);
              con.setDoOutput(true);
              con.setUseCaches(true);
              con.setRequestMethod("GET");
              // PrintWriter out = new PrintWriter(con.getOutputStream());
              BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
              String inputLine;
              int len = con.getContentLength();
              InputStream inn = con.getInputStream();
              byte[] buf = new byte[128];
              int c =0;
              System.out.print("len :"+len);
              System.out.print(inn.read());
              while( (c = inn.read())!= -1){
                   System.out.print(c);
    /*          while ((inputLine = in.readLine()) != null)
              System.out.println(inputLine);
              in.close();
              }catch(Exception e){
                   e.printStackTrace();
    Plaease help me to solve this problem. i want to send a file throuhg a servlet to my desktop program.
    Thanks in advance
    Ravi

    Give this a try:
    File strFile = new File(strFileName);
    long length = strFile.length();
    response.setContentType("application/octet-stream");
    response.setContentLength((int)length);
    response.setHeader("Content-Disposition", ("attachment; filename=" + strFileName));
    OutputStream out = response.getOutputStream();
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(strFile));
    int i = -1;
    while((i = in.read()) != -1) out.write(i);
    in.close();
    Kris

  • Write Files through return channel

    Hi,
    i'm newer in this forum. I'm working in a MHP project, and I want to comunicate STB with the server (in this case, a PC running Apache Server).
    The question is �can I write a file in the server with data obtained on the STB? I think that it is posible via return channel, but i'm not sure. The idea is to write file (on the server) with the solutions entered by TV user in an application that have some tests. �Are other ways besides return channel to do it?
    Thanks ;)
    Regards

    Hello here you an example of login in my application:
    package es.admin.servlet;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import es.admin.bd.PacienteBD;
    import es.admin.beans.Paciente;
    import es.admin.dao.PacienteDAO;
    * Servlet implementation class for Servlet: LoginPatient
    public class LoginPatient extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
       static final long serialVersionUID = 1L;
        /* (non-Java-doc)
          * @see javax.servlet.http.HttpServlet#HttpServlet()
         public LoginPatient() {
              super();
         /* (non-Java-doc)
          * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // TODO Auto-generated method stub
              processRequest(request,response);
         /* (non-Java-doc)
          * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // TODO Auto-generated method stub
              processRequest(request,response);
         private void processRequest(HttpServletRequest request,HttpServletResponse response) throws IOException
              Paciente paciente = new Paciente();
              paciente.setDni(request.getParameter("dni"));
              paciente.setContrasenia(request.getParameter("contrasenia"));
              boolean ok = PacienteBD.compruebaPaciente(paciente.getDni(),paciente.getContrasenia());
              response.setContentType("text/plain;charset=UTF-8");
              PrintWriter p = response.getWriter();
              if (ok)
                   p.println("true");
              else
                   p.print("false");
    public class PacienteBD {
         public static boolean compruebaPaciente(String dni,String password)
              boolean correcto = false;
              Paciente aux = PacienteDAO.BuscarPaciente(dni);
              if ((aux!=null)&&(aux.getContrasenia().equals(password)))
                   correcto = true;
              return correcto;
    }then you use from the java code :
    new URL ("http://admin/login?usuario=xxx&passw=xxx")
    thats all

  • How to parse the xml file using servlet

    My scenario is like this:
    <b>FILE-->XI-->J2EE Application</b>
    XI sends the xml file to j2ee application. My servlet receives the file in HTTPRequest string. 
    How to parse that file using servlets.I should get the xml file as it is and should be displayed in the browser.
    Can anyone please help me with code, its urgent.
    Please help me!

    Download this java code
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/work/Echo02.java
    in your servlet code you can write
    public void doPost(req,resp){
    DefaultHandler handler = new Echo02();
    handler.parse(req.getInputStream());
    Offcourse you will need to modify the code of Echo02 class a bit to suit your requirement which would finally retrun you a string and you can then write it using
    respose.getWriter().write(responseString);

  • How to read a file using servlet

    hi ,
    i've to read a file using servlet ,
    should read the file using servlet and display it in JSP,Could anybody get me how can i do it .
    Shiva

    To do that you need to get the response output stream and write yur file contents to that.
    response.setContentType(mimeType); //Set the mime type for the response
    ServletOutputStream sos = resp.getOutputStream();
    sos.write(bytes from your file input stream);
    sos.close();

  • File server servlet

    Hi all,
    I'm writing a servlet which has to serve images/picture's. For instance emoticons.
    I found the excellent help from [BalusC : FileServlet|http://balusc.blogspot.com/2007/07/fileservlet.html] The servlet itself works fine (Thank you BalusC)
    However it only servers the images from :
    $CATALINA_HOME/bin
    So if I ask for (for instance) http://localhost:8080/socnet/icons/cool_icon.gif it works only if $CATALINA_HOME/bin/icons/icon_cool.gif
    What I want is that this picture is served from the deployed application ($CATALINA_HOME/webapps/socnet/icons/icon_cool.gif)
    I can't seem to find how to accomplish this.
    So if anyone has any pointers...shoot
    Best Regards
    maboc

    Just to be sure....also the code from the servlet:
    public class fileserverservlet extends HttpServlet {
        private static final int DEFAULT_BUFFER_SIZE = 10240;
        private String filepath;
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            filepath = "icons";
            String requestedFile = request.getPathInfo();
            //is er daadwerkeleijk een file gevraagd?
            if (requestedFile == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            //File f = new File(filepath, URLDecoder.decode(requestedFile, "UTF-8"));
            File f = new File("icons/icon_cool.gif");
            if (!f.exists()) {
                System.out.println(f.getAbsoluteFile());
                System.out.println(f.getAbsolutePath());
                System.out.println(f.getCanonicalFile());
                System.out.println(f.getCanonicalPath());
                System.out.println(f.getName());
                System.out.println(f.getParent());
                System.out.println(f.getParentFile());
                System.out.println(f.getPath());
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            String contenttype = getServletContext().getMimeType(f.getName());
            if (contenttype == null) {
                contenttype = "application/octet-stream";
            response.reset();
            response.setBufferSize(DEFAULT_BUFFER_SIZE);
            response.setContentType(contenttype);
            response.setHeader("Content-Length", String.valueOf(f.length()));
            response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName() + "\"");
            BufferedInputStream input = null;
            BufferedOutputStream output = null;
            try {
                // Open streams.
                input = new BufferedInputStream(new FileInputStream(f), DEFAULT_BUFFER_SIZE);
                output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
                // Write file contents to response.
                byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                int length;
                while ((length = input.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
            } finally {
                // Gently close streams.
                close(output);
                close(input);
        }As you can see I do some checking with a lot of logging whether the file exists.
    A bit of the log file :
    /home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
    /home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
    /home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
    /home/martijn/apache-tomcat-6.0.26/bin/icons/icon_cool.gif
    icon_cool.gif
    icons
    icons
    icons/icon_cool.gif
    ...I don't have a clue whether the code is wrong or some tomcat startup parameter.

  • How to write files on Client Machine using JSP

    Hi,
    I am new to JSP. Please tell me how do i write files on Client machine thru a Browser.
    Please let me know at the Earliest.
    Thanks.
    Mehul Dave

    1) Well I find it rather convenient to deploy a web app as just one file rather than a bunch of files. For deployment it's much better. However I prefer using expanded files when developping (to use auto reload in Tomcat for example)
    2) It is a bad idea to upload files inside your webapp's context (ie: in it's deployment directory) because one day an uninformed system administrator might come and redeploy the web app and therefore delete all your uploaded files (believe me, I've already experienced this!)
    What i do usually is upload it in a completely different directory, something like /uploaded_files. Your uploaded files are therefore completely independant from your webapp
    However it is a bit trickyer to get those files back. Let's take the example of image uploads. You have 2 ways of proceeding:
    - the easiest : configure your web server (apache etc...) to redirect a certain url to your external directory. For example the /upload url will point to a /uploaded_files directory. This is easier to do and the fastest way to serve images but not always the best solution: you are dependant on the web server's configuration and you can't control the visibility on your files (no security constraints, anyone can see your uploaded files if they know the url).
    - you can also write a servlet which will load the file as an array of bytes and send it back in the response.
    You can call it this way :
    <img src="/serlvets/showmyimage?path=uploaded.gif">
    in this way you can control your uploaded files better: you may want to define security constraints on the visibity or not of uploaded files depending on the user which has logged on the site.

  • Session tracking for File Upload Servlet

    Hey Friends,
    I am developing a File Upload servlet and I need your help in certain matters .I have taken the servlet code from java-edge.com and am modifying it to give custom behaviour.I have a main page for upload (form upload)(lets call it form 1).If the file to be uploaded already exists on the server then a page is generated by the server saying that file already exists.(form 2)Now it is here(in form 2) that I want to provide an extra button which when submitted would recall the same servlet /or maybe another one and would provide the user for overriding the existing file.
    Now as per the code I would set the Override flag to be false in the second form and false in the main form .
    Given the case that it is a form based uploading servlet how do I maintain the user session when going to the next form or how do i pass the variables of the first form into second form .
    I am also facing another problem that is how do i manage multiple file uploads at a time .This basic system allows only one file per upload .
    P.S If someone could also throw some light on how to use the com.oreilly servlet (the latest version) it would be lovely but for now I want to focus on developing the current one

    Hi Jocelyn,
    I want to apologize firstly for the delay in my response.
    I was seriously bogged down due to certain circumstances and so couldnt reply.Thanks a million for your prompt reply.I'll post the Html content here and you will find the servlet code as is at the following U.R.L
    http://www.java-edge.com/Viewcode.asp?Value=serv012
    Form1:
    <HTML>
    <HEAD>
    <TITLE> Upload </TITLE>
    </HEAD>
    <BODY >
    <h2>Upload Your File!</h2>
    <form ENCTYPE="multipart/form-data" action="http://localhost:8080/servlet/Upload" method=post>
    click <b> browse </b>to select the file <br>
    <b> File:</b>
    <input type="FILE" name="Filename" value="" MAXLENGTH=255 size=50><br>
    Click here to upload!<input type=submit value=Upload>
    <input type=hidden name=Directory value="G:/Workspace/Upload/">
    <input type=hidden name=SuccessPage value="G:/Workspace/successpage.html">
    <input type=hidden name="OverWrite" value="false">
    <input type=hidden name="OverWritePage" value="">
    </form>
    </BODY>
    </HTML>
    Form 2
    <HTML>
    <HEAD>
    <TITLE> Upload </TITLE>
    </HEAD>
    <BODY >
    <h2>Upload Your File!</h2>
    <form ENCTYPE="multipart/form-data" action="http://localhost:8080/servlet/Upload" method=post>
    click <b> browse </b>to select the file <br>
    <b> File:</b>
    <input type="FILE" name="Filename" value="" MAXLENGTH=255 size=50><br>
    Click here to upload!<input type=submit value=Upload>
    <input type=hidden name=Directory value="G:/Workspace/Upload/">
    <input type=hidden name=SuccessPage value="G:/Workspace/successpage.html">
    <input type=hidden name="OverWrite" value="true">
    <input type=hidden name="OverWritePage" value="G:/Workspace/overwritepage.html">
    </form>
    </BODY>
    </HTML>
    Now in Form 2 I would add another button which when clicked would prompt the user if he wishes to overwrite the page.
    I am also posting the servlet code although I am sure u would prefer reading the one on the site
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class Upload extends HttpServlet
    static final int Max = 102400;// max. size of the file can be 100K
    String path;// stores path
    String msg;// store message of success
    //init method is called when servlet is first loaded
    public void init(ServletConfig config)throws ServletException
    super.init(config);
    if(path == null)
    path = "G:/Workspace/Upload/";
    if(msg == null)
    msg = "File successfully uploaded. Check out!";
    public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException
    ServletOutputStream sos = null;
    DataInputStream dis = null;
    FileOutputStream fos = null;
    try
    resp.setContentType("text/plain");// return type of response is being set as plain
    sos = resp.getOutputStream();// gets handle to the output stream
    catch(IOException e)
    System.out.println(e);
    return;
    try
    String contentType = req.getContentType();// gets client's content type that should be multipart/form-data
    if(contentType!=null && contentType.indexOf("multipart/form-data")!= -1)
         // gets handle to the input stream to get the file to be uploaded from client
         dis = new DataInputStream(req.getInputStream());
         // gets length of the content data
         int Length = req.getContentLength();
         if(Length>Max)// length of the content data is compared with max size set
         sos.println("sorry! file too large");
         sos.flush();
         return;
         //to store the contents of file in byte array
         byte arr[] = new byte[Length];
         int dataRead = 0;
         int totalData = 0;
         while(totalData <Length)
         dataRead = dis.read(arr,totalData,Length);
         totalData += dataRead;
         String data = new String(arr);//byte array converted to String
         arr = null;
         // gets boundary value
         int lastIndex = contentType.lastIndexOf("=");
         String boundary = contentType.substring(lastIndex+1,contentType.length());
         String dir = "";
         if(data.indexOf("name=Directory")>0)// the type ""Directory"" is searched in the web page
         dir = data.substring(data.indexOf("name=Directory"));
         //gets directory
         // the directory higher in the directory tree cannot be selected
         if(dir.indexOf("..")>0)
         sos.println("Error- the directory higher in the directory tree cannot be selected");
         return;
         String successPage="";
         if(data.indexOf("name=\"SuccessPage\"")>0)// the type ""SuccessPage"" is searched in the web page
         successPage =data.substring(data.indexOf("name=\"SuccessPage\""));
         // gets successpage
         String overWrite="";
         if(data.indexOf("name=\"OverWrite\"")>0)// the type ""Overwrite"" is searched in the web page
         overWrite =data.substring(data.indexOf("name=\"OverWrite\""));
         overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
         overWrite = overWrite.substring(overWrite.indexOf("\n")+1);
         overWrite = overWrite.substring(0,overWrite.indexOf("\n")-1);//gets overwrite flag
         else
         //overWrite = "false";
         String overWritePage ="";
         if(data.indexOf("name=\"OverWritePage\"")>0)// the type ""OverwritePage"" is searched in the web page
         // ensures same file is not uploaded twice
         overWritePage =data.substring(data.indexOf("name=\"OverWritePage\""));
         overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
         overWritePage = overWritePage.substring(overWritePage.indexOf("\n")+1);
         overWritePage = overWritePage.substring(0,overWritePage.indexOf("\n")-1);// // gets overwritepage
         //gets upload file name
         String file =data.substring(data.indexOf("filename=\"")+10);
         file = file.substring(0,file.indexOf("\n"));
         file = file.substring(file.lastIndexOf("\\")+1,file.indexOf("\""));
         int position;//upload file's position
         position =data.indexOf("filename=\"");//find position of upload file section of request
         position =data.indexOf("\n",position)+1;//find position of content-disposition line
         position =data.indexOf("\n",position)+1;//find position of content-type line
         position =data.indexOf("\n",position)+1;//find position of blank line
         int location =data.indexOf(boundary,position)-4;//find position of next boundary marker
         data =data.substring(position,location);// uploaded file lies between position and location
         String fileName = new String(path + dir + file);// the complete path of uploadad file
         File check = new File(fileName);
    /*************************CASE OVERRIDE ************************************/
         //String overwrite=req.getParameter("OverWrite");
         if(check.exists())// checks for existence of file
              if(overWrite.equals("false"))
                        if(overWritePage.equals(""))
                        sos.println("Sorry ,file already exists");
                        //return;
                        else
                        //overWritePage="G:/Workspace/overwritepage.html";
                        fos = new FileOutputStream(fileName);
                        fos.write(data.getBytes(),0,data.length());
                        //resp.sendRedirect(overWritePage);
                        sos.println("File Overridden");
              //return;
         File checkDir = new File(path + dir);
         if(!checkDir.exists())//checks for existence of directory
         checkDir.mkdirs();
    fos = new FileOutputStream(fileName);
    fos.write(data.getBytes(),0,data.length());
    sos.println("File successfully uploaded");
    if(check.exists())
              if(overWrite.equals("true"))
                   fos = new FileOutputStream(fileName);
                   fos.write(data.getBytes(),0,data.length());
                   if(successPage.equals(""))
                   sos.println(msg);
                   sos.println("File successfully uploaded");// if success HTML page URL not received
                   else
                   successPage="G:/Workspace/successpage.html";
                   resp.sendRedirect(successPage);
         else// incase request is not multipart
         sos.println("Not multipart");
    }//END OF TRY BLOCK
    catch(Exception e)
              try
              System.out.println(e);
              sos.println("unexpected error");
              catch(Exception f)
              System.out.println(f);
    finally
              try
              fos.close();// file output stream closed
              catch(Exception f)
              System.out.println(f);
              try
              dis.close();// input stream to client closed
              catch(Exception f)
              System.out.println(f);
              try
              sos.close();// output stream to client closed
              catch(Exception f)
              System.out.println(f);
    }//END OF DOPOST METHOD
    } //END OF CLASS
    Jocelyn the above code may have tid bit errors which u could understand.But I hope u get the overall idea of whats going on

  • JNI Invocation: open file in Java, write file in CPP

    Hello,
    Warning: I am a dunce, bad CPP code ahead!
    Using JNI invocation, I am trying to read a binary file in Java and write it in CPP.
    Everything compiles and runs without error, but the input and output jpg files are of course different.
    TIA to any help,
    kirst
    (begin ByteMe.java)
    import java.io.*;
    public class ByteMe
        // Returns the contents of the file in a byte array.
        public byte[] getBytesFromFile(String strInfo) throws IOException
            System.out.println("Testing:" + strInfo);
            File file = new File("1.jpg");
            InputStream is = new FileInputStream(file);
            // Get the size of the file
            long length = file.length();
            // Create the byte array to hold the data
            byte[] bytes = new byte[(int)length];
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            // Ensure all the bytes have been read in
            if (offset < bytes.length)
                throw new IOException("Could not completely read file "+file.getName());
            // Close the input stream and return bytes
            is.close();
            return bytes;
        public ByteMe()
              //System.out.println("in constructor");
    }(end ByteMe.java)
    (begin ByteMe.cpp)
    #include <stdlib.h>
    #include <string.h>
    #include <jni.h>
    #include <windows.h>
    // for file operations:
    #include <fstream>
    int main( int argc, char *argv[] )
         JNIEnv *env;
         JavaVM *jvm;
         JavaVMInitArgs vm_args;
         JavaVMOption options[5];
         jint res;
         jclass cls;
         jmethodID mid;
         jstring jstr;
         jobject obj_print;
         options[0].optionString = "-Xms4M";
         options[1].optionString = "-Xmx64M";
         options[2].optionString = "-Xss512K";
         options[3].optionString = "-Xoss400K";
         options[4].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
         vm_args.nOptions = 5;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         // Create the Java VM
         res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         if (res < 0)
              printf("Can't create Java VM");
              goto destroy;
         cls = env->FindClass("ByteMe");
         if (cls == 0)
              printf("Can't find ByteMe class");
              goto destroy;
         jmethodID id_construct = env->GetMethodID(cls,"<init>","()V");
         jstr = env->NewStringUTF(" from C++\n");
         obj_print = env->NewObject(cls,id_construct);
         // signature obtained using javap -s -p ByteMe
         mid = env->GetMethodID(cls, "getBytesFromFile", "(Ljava/lang/String;)[B");
         if (mid == 0)
              printf("Can't find ByteMe.getBytesFromFile\n");
              goto destroy;
         else
              jbyteArray jbuf = (jbyteArray) env->CallObjectMethod(obj_print,mid,jstr);
              jlong size = jsize(jbuf);
              printf("size is: %d\n", size); // size shown in output is
              std::ofstream out("data.jpg", std::ios::binary);
              out.write ((const char *)jbuf, 100000);     
         destroy:
             if (env->ExceptionOccurred())
                env->ExceptionDescribe();
        jvm->DestroyJavaVM();
    }(end ByteMe.cpp)

    Hello,
    Me again. Well, not such a dunce after all. Here is code that works correctly, and compiles with no errors and no warnings.
    Will much appreciate help with clean-up code.
    TIA,
    kirst
    (begin ByteMe.java)
    import java.io.*;
    public class ByteMe
        public long getFilezize(String strInfo) throws IOException
              // demonstrates String parameter passed from CPP to Java:
              System.out.println("(getFilesize) Hello world" + strInfo);
              File file = new File("1.bmp");
              InputStream is = new FileInputStream(file);
              // Get the size of the file
              long length = file.length();
              is.close();
              return length;
        // Returns the contents of the file in a byte array.
        public byte[] getBytesFromFile(String strInfo) throws IOException
            System.out.println("(getBytesFromFile) Hello world" + strInfo);
            File file = new File("1.bmp");
            InputStream is = new FileInputStream(file);
            // Get the size of the file
            long length = file.length();
            System.out.println("length is: " + String.valueOf(length));
            // Create the byte array to hold the data
            byte[] bytes = new byte[(int)length];
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
                offset += numRead;
            // Ensure all the bytes have been read in
            if (offset < bytes.length)
                throw new IOException("Could not completely read file "+ file.getName());
            // Close the input stream and return bytes
            is.close();
            return bytes;
        public ByteMe()
              //System.out.println("in constructor");
    }(end ByteMe.java)
    (begin ByteMe.cpp)
              Signature obtained with command:
                   "C:\Program Files\Java\jdk1.5.0_15\bin\javap.exe" -s -p ByteMe
                   Compiled from "ByteMe.java"
                   public class ByteMe extends java.lang.Object{
                   public long getFilezize(java.lang.String)   throws java.io.IOException;
                     Signature: (Ljava/lang/String;)J
                   public byte[] getBytesFromFile(java.lang.String)   throws java.io.IOException;
                     Signature: (Ljava/lang/String;)[B
                   public ByteMe();
                     Signature: ()V
         Compiled VC++ 2005 Express, run on Vista
    #include <stdlib.h>
    #include <string.h>
    #include <jni.h>
    // file operations
    #include <fstream>
    int main( int argc, char *argv[] )
         JNIEnv *env;
         JavaVM *jvm;
         JavaVMInitArgs vm_args;
         JavaVMOption options[5];
         jint res;
         jclass cls;
         jmethodID mid;
         jmethodID sizeid;
         jstring jstr;
         jobject obj_print;
         jlong filesize;
         options[0].optionString = "-Xms4M";
         options[1].optionString = "-Xmx64M";
         options[2].optionString = "-Xss512K";
         options[3].optionString = "-Xoss400K";
         options[4].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
         vm_args.nOptions = 5;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         // Create the Java VM
         res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         if (res < 0)
              printf("Can't create Java VM");
              goto destroy;
         cls = env->FindClass("ByteMe");
         if (cls == 0)
              printf("Can't find ByteMe class");
              goto destroy;
         jmethodID id_construct = env->GetMethodID(cls,"<init>","()V");
         printf("%s\n",id_construct);
         jstr = env->NewStringUTF(" from C++!\n");
         if (jstr == 0)
              // Normally not useful
              printf("Out of memory (could not instantiate new string jstr)\n");
              goto destroy;
         obj_print = env->NewObject(cls,id_construct);
         //BEGIN BLOCK to get file size
         sizeid = env->GetMethodID(cls, "getFilezize", "(Ljava/lang/String;)J");
         if (sizeid == 0)
              printf("Can't find ByteMe.getFilezize\n");
              goto destroy;
         else
              printf("got here\n");
              filesize =(jlong) env->CallObjectMethod(obj_print,sizeid,jstr);
              printf("got filesize\n");
         // END BLOCK to get file size
         // BEGIN BLOCK to write file
         mid = env->GetMethodID(cls, "getBytesFromFile", "(Ljava/lang/String;)[B");
         if (mid == 0)
              printf("Can't find ByteMe.getBytesFromFile\n");
              goto destroy;
         else
              jbyteArray ret =(jbyteArray) env->CallObjectMethod(obj_print,mid,jstr);
              // Access the bytes:
              jbyte *retdata = env->GetByteArrayElements(ret, NULL);
              // write the file
              std::ofstream out("data.bmp", std::ios::binary);
              //out.write ((const char *)retdata, 921654);
              out.write ((const char *)retdata, (long)filesize);
         // END BLOCK to write file
         destroy:
             if (env->ExceptionOccurred())
                env->ExceptionDescribe();
        jvm->DestroyJavaVM();
    }(end ByteMe.cpp)

  • How to write Header and Footer elements in Write file Adapter

    Hi,
    I have a requirement to write the file.The write file contains header and footer elements ,how we can write these elements. These elements are fixed for all files.these are not come from any input.below is the sample file.
    $begintable
    name,Id,Desg
    ad,12,it
    $endtable

    Hi,
    I have created the XSD for you, and i created a sample SOA Composite which writes the file same like what you want, the below XSD can write a file with one header record, multiple data records and one trailer record.
    <?xml version="1.0" encoding="UTF-8" ?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:nxsd="http://xmlns.oracle.com/pcbpel/nxsd"
    xmlns:tns="http://TargetNamespace.com/WriteFile"
    targetNamespace="http://TargetNamespace.com/WriteFile"
    elementFormDefault="qualified" attributeFormDefault="unqualified"
    nxsd:version="NXSD" nxsd:stream="chars" nxsd:encoding="UTF-8">
    <xsd:element name="Root-Element">
    <xsd:complexType>
    <!--xsd:choice minOccurs="1" maxOccurs="unbounded" nxsd:choiceCondition="terminated" nxsd:terminatedBy=","-->
    <xsd:sequence>
    <xsd:element name="RECORD1">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="header" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy="${eol}"
    nxsd:quotedBy='"'/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="RECORD2" minOccurs="1" maxOccurs="unbounded">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="data1" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy=","
    nxsd:quotedBy='"'/>
    <xsd:element name="data2" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy=","
    nxsd:quotedBy='"'/>
    <xsd:element name="data3" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy="${eol}"
    nxsd:quotedBy='"'/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    <xsd:element name="RECORD4" nxsd:conditionValue="$endtable">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="trailer" type="xsd:string"
    nxsd:style="terminated" nxsd:terminatedBy="${eol}"
    nxsd:quotedBy='"'/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>
    Hope this helps,
    N

  • Is it possible to create a file in servlet context? pls help me

    Is it possible to create a file in servlet context? pls help me

    Surely it is possible.File file = new File(path, name);

  • Uploading a file in Servlets

    I need help in uploading a file using servlets.help

    http://search.java.sun.com/search/java/index.jsp?col=ja
    aforums&qp=&qt=servlet+file+uploadThats a Master Link!!

  • Error while relocating (Can't write file (no space)) - Help please

    I have been having trouble relocating master files since upgrading to Leopard. The problem doesn't seem to affect only Aperture. I can happen when using Finder or another application to move files from one drive to another. Other types of files don't seem to be affected, just my library of image files.
    The copy operation runs for a while then hangs up. The application doing the copy reports an error that that's the end. Aperture gives this error message: Error while relocating (Can’t write file (no space)). The Finder reports plenty of available space on the destination drive!
    I remember seeing a thread--but can't find it now--about a problem with certain xmp metatdata embedded into files causing problems with file operations.
    Hoping for a solution!
    Message was edited by: thomas80205

    It's possible that you might have a corrupt file. Have you tried to copy different files on to the destination drive? If those files copy fine, then narrow down the offending file by copying less images at a time.

Maybe you are looking for