Servlet coding - writing file to server

Hi,
I am using IBM's RAD as my IDE. In my servlet, I have coded:
                    // set the filename for the server side repository ...
                    serverFileName = "/web/UserSource/" + user + "-" + shortFileName;
                    // Open up the output file on server ...
                    FileOutputStream fos = new FileOutputStream(serverFileName);
                    Writer outf = new OutputStreamWriter(fos,"Cp1047");The above logic is inside an "if" construct, as I only can set the file name after some information is retrieved.
Afterwards, outside of this "if", I try to write to the file like so, (another "if"):
               if (cnt > 4 && !prevLine.equals(boundary)) {
                    outf.write(prevLine);
                    out.println("<br>" + prevLine);
               }The outf.write(prevLine) statement is flagged as "outf cannot be resolved"
why, since I have previously defined it?

The above logic is inside an "if" construct, as I
only can set the file name after some information is
retrieved.
Afterwards, outside of this "if", I try to write to
the file like so, (another "if"):
               if (cnt > 4 && !prevLine.equals(boundary)) {
                    outf.write(prevLine);
                    out.println("<br>" + prevLine);
The problem is the scope of outf. Since it is declared in an if block, it goes out of scope when that block is exited, so it's no longer available after the first if. Declare the variable outside the if, so that it's still in scope when you get to the next if block.
FileOutputStream fos;
if (whatever) {
    FileOutputStream fos = new FileOutputStream(serverFileName);
if (whatever) {
    outf.write(prevLine);
}Message was edited by:
hunter9000

Similar Messages

  • ORA-29283 when writing file to server

    I am trying to setup procedure that writes the result of a query to a file on the database server. I am currently testing the writing of file using some generic code.
    The database is on Red Hat Linux. The directory was created on the server as the mfts_user account and the oracle user granted read/write access. This was verified by logging into the server as oracle and creating a file via "touch test.txt".
    The following 2 procedures/functions were created to test utl_file:
    create or replace FUNCTION dump_csv ( p_query IN VARCHAR2
    , p_separator IN VARCHAR2 DEFAULT ','
    , p_dir IN VARCHAR2
    , p_filename IN VARCHAR2)
    RETURN NUMBER
    AS
    l_output utl_file.file_type;
    l_thecursor INTEGER DEFAULT dbms_sql.open_cursor;
    l_columnvalue VARCHAR2(2000);
    l_status INTEGER;
    l_colcnt NUMBER DEFAULT 0;
    l_separator VARCHAR2(10) DEFAULT '';
    l_cnt NUMBER DEFAULT 0;
    BEGIN
    l_output := utl_file.fopen(p_dir, p_filename, 'w');
    dbms_sql.parse(l_thecursor, p_query, dbms_sql.native);
    FOR i IN 1 .. 255
    LOOP
    BEGIN
    dbms_sql.define_column(l_thecursor, i, l_columnvalue, 2000);
    l_colcnt := i;
    EXCEPTION
    WHEN others
    THEN
    IF(SQLCODE = -1007) THEN
    EXIT;
    ELSE
    RAISE;
    END IF;
    END;
    END LOOP;
    dbms_sql.define_column(l_thecursor, 1, l_columnvalue, 2000);
    l_status := dbms_sql.EXECUTE(l_thecursor);
    LOOP
    EXIT WHEN(dbms_sql.fetch_rows(l_thecursor) <= 0);
    l_separator := '';
    FOR i IN 1 .. l_colcnt
    LOOP
    dbms_sql.column_value(l_thecursor, i, l_columnvalue);
    utl_file.put(l_output, l_separator || l_columnvalue);
    l_separator := p_separator;
    END LOOP;
    utl_file.new_line(l_output);
    l_cnt := l_cnt + 1;
    END LOOP;
    dbms_sql.close_cursor(l_thecursor);
    utl_file.fclose(l_output);
    RETURN l_cnt;
    END dump_csv;
    create or replace PROCEDURE TEST_DUMP_CSV
    AS
    l_count NUMBER;
    l_fn VARCHAR2(30);
    BEGIN
    SELECT TO_CHAR(SYSDATE,'YYYYMMDDHH24MISS') INTO l_fn FROM DUAL;
    l_count := dump_csv( p_query => 'select * from coreq',
    p_separator => ',',
    p_dir => 'OUTBOUND_NEW_DIR',
    p_filename => 'dump_csv' || l_fn || '.csv' );
    dbms_output.put_line( to_char(l_count) || ' rows extracted to file dump_csv' || l_fn || '.csv.' );
    END TEST_DUMP_CSV;
    To test utl_file, I execute as the MAXIMO user:
    CREATE OR REPLACE DIRECTORY outbound_new_dir AS '/home/mfts_user/Maximo/outbound_new';
    select dump_csv('select * from coreq', ',', 'OUTBOUND_NEW_DIR', 'dump_csv.csv' ) from dual;
    Here is the error I get:
    ORA-29283: invalid file operation
    ORA-06515: at "SYS.UTL_FILE", line 449
    ORA-29283: invalid file operation
    ORA-06512: at "MAXIMO.DUMP_CSV", line 15
    ORA-06512: at line 1
    This same setup works on Windows XP when logged in as an Admin user, which tells me that the syntax and logic is correct.
    What could be wrong with the Linux setup?

    Yes. I read that read/write is automatically granted to the user that creates the DIRECTORY object.
    The result of the query you gave was 2 records:
    GRANTOR GRANTEE TABLE_SCHEMA TABLE_NAME PRIVILEGE GRANTABLE HIERARCHY
    SYS     MAXIMO     SYS     OUTBOUND_NEW_DIR     READ     YES     NO
    SYS     MAXIMO     SYS     OUTBOUND_NEW_DIR     WRITE     YES     NO

  • Out of disk space when copying files from server to server

    Servers: NW 5.1.7
    Workstation: Windows 98SE with client32 v3.4
    There is a batch file that copies files from server A to server B. At certain point, the copying gets stuck and message is displayed on the workstation: ""Network Status. Client32: out of disk space writing file to server B." Unless I press OK, the copying will not continue. There's plenty of space and memory, no quotes or user restrictions on server B. This procedure worked for years without any problem and nothing was altered on the servers or workstation at time of occurrence.

    Did you purge the volumes ?
    How high is ratio between compressed and noncompressed data on volumes?
    I assume, that for this usage (copy one server to another) you should
    seek the different way (program), which transfer the compressed data
    with untouched state of compression.
    Jindrich Kovar
    Marty Fox napsal(a):
    > Servers: NW 5.1.7
    > Workstation: Windows 98SE with client32 v3.4
    > There is a batch file that copies files from server A to server B. At certain point, the copying gets stuck and message is displayed on the workstation: ""Network Status. Client32: out of disk space writing file to server B." Unless I press OK, the copying will not continue. There's plenty of space and memory, no quotes or user restrictions on server B. This procedure worked for years without any problem and nothing was altered on the servers or workstation at time of occurrence.

  • Writing to file on server from applet

    ok i know this issue has been dealt with on numerous occasions but i would like someone to explain me in details what would be the best way of doing it.
    I know that one way of doing it is having a servlet which would perform I/O and would communicate with the applet via a socket. What I don't understand is when and how does the servlet start running.
    It has to be running to be able to first accept a connection from the applet and then listen on the specified port.
    So how does the servlet start running so as to be able to communicate with the applet?
    Could you please make your answers as precise as possible.
    Thanks

    Servlets are run by servlet containesr. You must start container first (Tomcat, Jetty, Weblogic, Websphere, ...) and then it will handle running servlet. Usually it is a first http-request that instantiates servlet on-demand, but you may configure it to be instantiated at container startup. So, only you have to worry about is to put servlet on container server and it will take care of the rest.
    Simple writing to a server-side file is easier to do with PHP if you have linux/unix-based web server. Just installing a servlet container for it might be a bit overkill.

  • WebLogic server's charset for writing files

    Hi!
    I have the following situation. Webapp (servlet) instantiates a class, which periodically writes data to files. The data is written to a file using the following code:
    fos = new FileOutputStream(outfile);
    //Don't wanna specify charset here
    fos.write(line.getBytes());
    The question is, where do I specify the charset to be used? Weblogic-application.xml has the following definition:
    <application-param>
    <param-name>webapp.encoding.default</param-name>
    <param-value>UTF-8</param-value>
    </application-param>
    Should this define also the encoding used when writing files, or should I define it in the server startup somehow, or what?

    Hi!
    I have the following situation. Webapp (servlet) instantiates a class, which periodically writes data to files. The data is written to a file using the following code:
    fos = new FileOutputStream(outfile);
    //Don't wanna specify charset here
    fos.write(line.getBytes());
    The question is, where do I specify the charset to be used? Weblogic-application.xml has the following definition:
    <application-param>
    <param-name>webapp.encoding.default</param-name>
    <param-value>UTF-8</param-value>
    </application-param>
    Should this define also the encoding used when writing files, or should I define it in the server startup somehow, or what?

  • Writing files to another server

    Hi,
    I need help or ideas with writing files (1 text and 1 image) from my servlet to a share/location on another server.
    How can this be achieved?

    Hello,
    1. Shared drives between both servers.
    2. You need to write some remote service [WebService, RMI, EJB] on the second server listening on a port and which can receive the information you send through.
    Thanks,
    Paz

  • Uploading a file to server using servlet (Without using Jakarta Commons)

    Hi,
    I was trying to upload a file to server using servlet, but i need to do that without the help of anyother API packages like Jakarta Commons Upload. If any class for retrieval is necessary, how can i write my own code to upload from client machine?.
    From
    Velu

    <p>Why put such a restriction on the solution? Whats wrong about using that library?
    The uploading bit is easy - you put a <input type="file"> component on the form, and set it to be method="post" and enctype="multipart/form-data"
    Reading the input stream at the other end - thats harder - which is why they wrote a library for it. </p>
    why i gave the restriction is that, i have a question that <code>'can't we implement the same upload'</code>
    I was with the view that the same can be implemented by our own code right?

  • How can i upload a image file to server by using jsp or servlet.

    Hi,
    I m gurumoorthy. how can i upload a image file to server by using jsp or servlet without using third party API. pls anyone send me atleast outline of the source code.
    Pls send me anyone.
    Regards,
    Gurumoorthy.

    I'm not an applet programmer so I can't give you much advice there.
    If you want to stream the file from the server before it's entirely uploaded, then I don't believe you can treat it like a normal file. If you're just wanting to throw it up there and then listen to it, then you can treat it like a normal file.
    But again, I'm not entirely certain. You might be able to stream the start of the file from the server while you're still uploading the end of it, but it probably depends on what method you're using to do the transfer.

  • Connection refused Error while writing file to FTP server.

    Hi All,
    We got below error while writing file to FTP server. Any one have any idea on this?
    sABCS_1.0_8e88588d4fb54ebd2ac7ef66c8421d52.tmp/writeEncryptedFile.wsdl [ Put_ptt::Put(opaque) ] - Could not invoke operation 'Put' against the 'FTP Adapter' due to:
    ORABPEL-11429
    Error sending file to FTP Server.
    Unable to send file to server. [Caused by: Connection refused]
    Please ensure 1. Specified remote output Dir has write permission 2. Output filename has not exceeded the max chararters allowed by the OS and 3. Remote File System has enough space.

    Hmmm ...
    Same issue as your post from three months' earlier?
    Re: Error while putting file in sftp location.

  • How to upload a file into server using j2ee jsp and servlet with bean?

    How to upload a file into server using j2ee jsp and servlet with bean? Please give me the reference or url about how to do that. If related to struts is more suitable.
    Anyone help me please!

    u don't need j2ee and struts to do file uploading. An example is as such
    in JSP. u use the <input> file tag like
    <input type="file"....>You need a bean to capture the file contents like
    class FileUploadObj {
        private FormFile srcFile;
        private byte[] fileContent;
        // all the getter and setter methods
    }Then in the servlet, you process the file for uploading
        * The following loads the uploaded binary data into a byte Array.
        FileUploadObj form = new FileUploadObj();
        byte[] byteArr = null;
        if (form.signFile != null) {
            int filesize = form.srcFile.getFileSize();
            byteArr = new byte[filesize];
            ByteArrayInputStream bytein = new ByteArrayInputStream (form.srcFile.getFileData());
            bytein.read(byteArr);
            bytein.close();
            form.setFileContent(byteArr);
        // Write file content using Writer class into the destination file in the server.
        ...

  • Servlet not executing the a file at server?

    i am trying to execute a java file at server
    using the following servlet. I am using
    Process proc=runtime.exec("C:\\j2sdk1.4.1_01\\bin\\javac HelloServlet.java"); I am compiling the code succesfully
    and when i call the servlet at browser it displays HELLO
    but not executing the command. I am using Tomcat and winows NT.
    here the servlet code ....please help.........
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Hello extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n";
    out.println(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>Hello</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
    "<H1>Hello</H1>\n" +
    "</BODY></HTML>");
    try
    Runtime runtime=Runtime.getRuntime();
    Process proc=runtime.exec("C:\\j2sdk1.4.1_01 \\bin\\javac HelloServlet.java");
    BufferedReader br=new BufferedReader(new InputStreamReader(proc.getInputStream()));
    PrintWriter com_out=response.getWriter();
    com_out.println("<pre>");
    String line=null;
    while((line=br.readLine())!=null)
    { com_out.println(line);
    catch (Exception e)
    out.println("Listener *not* started!");

    thanku for the cooperation. i kept as below but still it is not working.......
    String path = getServletContext().getRealPath("C:\\Tomcat 4.1\\webapps\\examples\\WEB-INF\\classes\\Hello.class");
    Runtime runtime=Runtime.getRuntime();
    Process proc=runtime.exec("C:\\j2sdk1.4.1_01\\bin\\javac HelloServlet.java" +path );                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Need HELP!! Where I have to place an web.xml(servlet) file on server

    I'm using E-business suite for oracle HR version 11.
    On localhost i have developed an servlet file with using web.xml. On web.xml i have customized the file that can load a class for my servlet.But when I deploy on the server i had a cnfused wher do i have to place web.xml and my servlet.
    I have made an servlet file for my custom. Where do I have to place an xml(servlet) file on server?
    Would you give me know forsolving my problem.Please give me know,I really appreciated if you want to give some solution.
    Regards,
    Dany Fauzi

    Copy web.xml to WEB-INF directory of the web application.

  • Writing data to a file in Server

    Hi all,
    In my application i would be writing data to a file which is located in the Server.
    when i tried writing data to a file in my local machine using a Java Application it worked fine .
    Now through the webdynpro application and providing the files path (in server ) ,i am getting file not found exception .
    I am using basic File and i/o operations .
    File abc = new File ("
    servernamer
    folder1
    subfolder1
    filename.dat");
    when i try accessing this path from the command prompt its opening fine.
    Could you please through some light on this .
    thanks,
    swetha .

    >
    KalluriVijay wrote:
    > Hi Swetha,
    > Do one think.
    > InputStream text = null;
    >                int temp = 0;
    >                //File file = new File(wdContext.currentContextElement().getResource().getResourceName().toString());
    >                //wdComponentAPI.getMessageManager().reportSuccess("filePath Vijay:::"+file);     
    > //wdComponentAPI.getMessageManager().reportSuccess("filePath Vijay:::");
    >                     try
    >                     {
    >                     String fileName = wdContext.currentContextElement().getResource().getResourceName().toString();               
    >                     if(fileName.equalsIgnoreCase("ASNCRT.dat"))
    >                     {     
    >                     File file = new File(fileName);                         
    >                     FileOutputStream op = new FileOutputStream(file);          
    >                     if (wdContext.currentContextElement().getResource()!= null)
    >                     {
    >                     text = wdContext.currentContextElement().getResource().read(false);
    >                     while((temp=text.read())!= -1)
    >                     {
    >                     op.write(temp);
    >                     }
    >                     }
    >                     op.flush();
    >                     op.close();
    >                     path = file.getAbsolutePath();
    >                     //wdComponentAPI.getMessageManager().reportSuccess(path);
    >                     }
    >                     else
    >                     {
    >                     wdComponentAPI.getMessageManager().raiseException("Please Check the Filename:Filename should be ASNCRT.dat ",true);     
    >                     }
    >                     }
    >                     catch(Exception ex)               
    >                     {
    >                     ex.printStackTrace();
    >                     }
    > By using this code u can put u r file in to Server Path, then u will get the that .dat file from server path and run the command prompt its opening fine
    > How to get the file from the Server Path:
    > Workbook wb = Workbook.getWorkbook(new File(path));     // For get the file from the Server path
    >
    >   Hope this is help full for u
    > Regards
    > Vijay Kalluri
    This won't work. First, like i said, File class is not for accessing remote files, it is only for local files.
    Second, Workbook class is a class from Java Excel API. He is not working with xls. Anyway that wouldn't work either.

  • How to copy file from server to another machine in network through JSP

    Hello!
    any body can solve my problem.
    i m working in JSP. i want to copy a file from server on which JSP engine is running to another computer in the same network.
    i used Java File Object to copy file from one machine to another in network. and its working fine on network. but the problem is when i used the same code in web page there is exception which is Access is Denied. what i should do now.
    i m writing the code i m using in my JSP page
    String fileToCopy = "C:/oracle/Apache/Apache/htdocs/FAO/FAO_MiddleFrame.jsp";
         String destinationDir = "\\\\af09\\c";
    File source = new File(fileToCopy);
    String fileName1 = source.getName();
    if ((!destinationDir.endsWith("\\")) && (!destinationDir.endsWith("/"))) {
    destinationDir = destinationDir + "\\";
    File destination = new File(destinationDir + fileName1);
    if (!destination.exists()) {
    if (!destination.createNewFile()) {
    //throw new IOException("Unable to create file. May be you don't have permissions.");
    byte[] buffer = new byte[1024];
    FileInputStream in = new FileInputStream(source);
    FileOutputStream outStream = new FileOutputStream(destination);
    int bytesRead = 0;
    while ((bytesRead = in.read(buffer)) != -1) {
    outStream.write(buffer, 0, bytesRead);
    out.println("File copied successfully ....");
    plz reply me as soon as possible.
    i will be very thankful
    Saad

    Thats the way it works. Cause servlet contaner doesnot allow other machines in the network to access other than machine which it came from as in case of applets. What you can do is if the other machine is also based on webserver or app server .. you can upload the file as it gets to that page do the process.
    I would like to hear more on my comments..
    Suggestions ??
    Ban

  • How to download a file from server machine to client machine using jsp

    Hi,
    In my application, I have an excel file stored on my server machine. How can I download that excel file on to my client machine using jsp. Is there any other way I can open that file from my machine and save it in my machine using jsp/java?
    Its an emergency for me to do this.
    Can anyone provide me the full code to download a file from server machine as I don't have
    time to browse through various sites.
    thanks in advance,
    Tiijnar

    Please post your code using code tags (click on CODE above the text area, when posting)
    response.setContentType("application/octet-stream");Why octet-stream? Set the correct mime-type.
    String disHeader = "Attachment; Filename=\"filename\"";The filename should just be the file's name. Not the complete path to the file! This will tell anyone where the file is located on the server. It's also inconvenient because by default,the browser will suggest it as the name for the download.
    Your way of writing to the output stream is just plain wrong. See this snippet (picked from [http://balusc.blogspot.com/2007/07/fileservlet.html])
            BufferedInputStream input = null;
            BufferedOutputStream output = null;
            try {
                // Open streams.
                input = new BufferedInputStream(new FileInputStream(file), 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);
                // Finalize task.
                output.flush();
            } finally {
                // Gently close streams.
                close(output);
                close(input);
            }

Maybe you are looking for

  • How to get the Output File Name as One of the Field Value From Payload

    Hi All, I want to get the Output file name as one of the Field value from payload. Example: Source XML <?xml version="1.0" encoding="UTF-8" ?> - <ns0:MT_TEST xmlns:ns0="http://sample.com"> - <Header>   <NAME>Bopanna</NAME>   </Header>   </ns0:MT_TEST

  • Name of the programme, which writes PO Output IDOC into a file

    Hello Guru's, Will anyone know the name of the Program which writes the Purchase Order Output Medium IDOC into a file ( xl file, text file etc,.) in SAP.

  • How to: CSV file with a graph.

    Hi guys here's a simple prg that writes a CSV file. Question: is it possible to produce a graph from the program? Or in other words, when opening the file, is it possible to see the values AND the graph ? import java.io.*; class Example      /* Main

  • Mass update of cost element description - edit a table

    Hi Folks, i would like to know wich is the best way to update thousand of description of cost element! this is due to the fact that i have 4 differents languages to manage....so every time it's necessary to enter them in 4 languages, but the problem

  • Reg: Process Flow of WMS

    Dear All I'm a MM consultant. I would like to know about the Process flow,Master data & Organization structure of WMS. pl help me Thanks pavan