File Writing with JSP

Hi all,
I'm creating a simple app that gets form data and populates it to a file. I want to make sure that each instance (thread?) is able to write to the file and not throw an exception since the file may be currently open by another instance of the jsp. Now I did basic thread programming in C++ a long time ago, so I'm aware of thread waiting conceptually, but I'm not familiar with the java implementation. Can someone show me some basic syntax on how I would go in essentially putting a lock on the file writing portion of the code.
Thanx much

I disagree that you should override anything in Threa, especiially the sleep method.
What you should do is handle the file writing in a producer/consumer fashion. Have a single class that extends Runnable be the consumer. It handles all the file writing issues. You will run this in its own thread.
Your JSPs (or other threads) fill in a collection, or some other holder, which informs the consumer to write to the file.
As a brief example, this is a mini logger type of program. I use a class (LogCenter) to log data put in it from other sources (client1 and client2). For the sake of using newer API, I make use of the java.util.concurrent.BlockingQueue (and java.util.concurrent.LinkedBlockingQueue) to make a thread-safe collection and reporting system for text to come in and out of the logger.
Note, this is far from production. Just something I whipped up when playing with blocking queues a while ago...
package net.thelukes.steven.thread.test;
import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class LoggingCenter implements Runnable {
  private PrintWriter output;
  private BlockingQueue<String> toPrint;
  public LoggingCenter() {
    toPrint = new LinkedBlockingQueue<String>(10);
  public void setOutput(PrintWriter pw) {
    if (pw == null)  {
      if (output != null)
        return; //do not replace output with null
      else //pw is null and output is null
        throw new IllegalArgumentException("Ouput PrintWriter must not be NULL");
    else {
      if (output != null) closeOutput(); //if output exists already, close it.
      output = pw;
  public void log(String text) {
    boolean added = false;
    while (!added)
      try {
        toPrint.put(text);
        added=true;
      } catch (InterruptedException ie) {
        ie.printStackTrace();
        try { Thread.sleep(300L); }
        catch (InterruptedException ie2) { ie2.printStackTrace();}
  public void run() {
    try {
      while (true) {
        printLn(toPrint.take());
    } catch (InterruptedException ie) {ie.printStackTrace();}
  private void closeOutput() {
    output.flush();
    output.close();
  private void printLn(String text) {
    if (output == null)
      throw new IllegalStateException
        ("The Output PrintWriter must be set before any output can occur.");
    output.println(text);
    output.flush();
package net.thelukes.steven.thread.test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class LoggingTest {
  public static void main(String[] args) throws IOException {
    PrintWriter output = new PrintWriter(
      new FileWriter(new File("log.txt")));
    //PrintWriter output = new PrintWriter(System.out, true);
    final LoggingCenter logger = new LoggingCenter();
    logger.setOutput(output);
    Thread t = new Thread(logger);
    t.start();
    Thread client1 = new Thread(
        new Runnable() {
          public void run() {
            while (true) {
              logger.log("Client 1: "+System.currentTimeMillis());
              try {
                Thread.sleep(1250L);
              } catch (InterruptedException e) {}
    Thread client2 = new Thread(
        new Runnable() {
          public void run() {
            while (true) {
              logger.log("Client 2: "+System.currentTimeMillis());
              try {
                Thread.sleep(2500L);
              } catch (InterruptedException e) {}
    client1.start();
    client2.start();
}

Similar Messages

  • Including static html file (WebServer)  with JSP (App server)?

    Hi,
    I want to know how can a static html file that runs on a Web Server (iPlanet) in a JSP that runs on an App Server (WebLogic 6.1).
    What would be the tag used and how the html file is referenced? Is there any other extra settings involved while integrating iPlanet with WebLogic 6.1?
    Responses are highly appreciated.
    Thanks and Regards,
    Madanlal.

    Web servers usually work with the MIME Types. In the mime type settings will determine how a request for a particular mime type is served. Usually HTML, JPG,GIF... are served by the web server itself. A JSP request will be forwarded to the APP Server for peocessing.
    The HTML and the image files need to be in a directory visible to the web server from the document root.
    See the files
    config\mime.types
    config\obj.conf
    under the web server installation directory.
    Refer to the web server's admin guide for more info.

  • File download with JSP

    I have found some code within this forum that I have been attempting to use to allow customers to download text files to their PC's. The code below is what I have come up with from my understandings on exactly how it should work, but it just will not work ...
    Am I correct in assuming that the file that I want to make available for download is specified within the File f = new File(path+filename); section???
    I have made the path variable refer directly to the file system (/disk2/invoice/) as well as via http (http://domain.com/invoice/) but it will not work !!!
    It returns the save/open dialog but as soon as I select an option it returns a windows error prompt as follows:
    Internet Explorer cannot download ...p?filename=123414_76453_437 from www.domain.com.
    Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.
    Can someone please tell me, where am I supposed to reference the file to be downloaded and how am I to reference it ???
    <%
    // get the file name from the calling page
    String filename = request.getParameter("filename");
    //get the file path to the file I want to make available via download
    String path = getServletContext().getInitParameter("invoicePath");
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
    int iRead;
    FileInputStream stream = null;
    try {
         File f = new File(path+filename);
         stream = new FileInputStream(f);
         while ((iRead = stream.read()) != -1) {
              out.write(iRead);
         out.flush();
    finally {
         if (stream != null) {
              stream.close();
    %>
    <%@ page import="java.io.*,javax.servlet.*,java.util.* " contentType="text/html" %>
    <html>
    finally we have success ...     
    </html>

    For those of you who are still having issues that have been unresolved trying to download a file from a webserver to a client, I have finally figured out how to do so ...
    The following code now works for me on Solaris running Tomcat 3.1 and on W2K running JRun 3.2 ...
    Issue 1: I specified a contentType=text/html in the page specification ... This must be removed ...
    <%@ page ... contentType=text/html%>
    Issue 2: The new File() reference must be a direct path to the file on the operating system. This does not work if it is referenced with a http path.
    Other than that, I have included the code that I use to make files available for download on our webserver.
    <%@ page import="java.io.*,javax.servlet.*,java.util.* "%>
    <%
    // get the file name
    String filename = request.getParameter("filename");
    //get the file path
    String path = getServletContext().getInitParameter("invoicePath");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
    int iRead;
    FileInputStream stream = null;
    try {
         File f = new File("/disk2/wwwhome/psmerged/invoice/" + filename);
         stream = new FileInputStream(f);
         while ((iRead = stream.read()) != -1) {
              out.write(iRead);
         out.flush();
    finally {
         if (stream != null) {
              stream.close();
    %>

  • File upload with jsp

    I am trying to upload a file to a mysql database (using a jsp tomcat 4.1 container) for each new member of my website (typically a cv which is a .rtf word file). I have used the example on the oreilly page and have managed to get the image of the file I have uploaded. Now I am trying to save this into my database for each member so that they can enter all of their details on the one page i.e. name age etc and also a browse for file button which will store the path of their file on their computer. When they click the submit button, all of their details are then stored into the database by the resultant page which outputs wehter they have been successful or not.
    The upload bean code (from the oreilly site):
    package com.idhcitip;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.ServletInputStream;
    import java.util.Dictionary;
    import java.util.Hashtable;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public class FileUploadBean {
    private String savePath, filepath, filename, contentType;
    private Dictionary fields;
    public String getFilename() {
    return filename;
    public String getFilepath() {
    return filepath;
    public void setSavePath(String savePath) {
    this.savePath = savePath;
    public String getContentType() {
    return contentType;
    public String getFieldValue(String fieldName) {
    if (fields == null || fieldName == null)
    return null;
    return (String) fields.get(fieldName);
    private void setFilename(String s) {
    if (s==null)
    return;
    int pos = s.indexOf("filename=\"");
    if (pos != -1) {
    filepath = s.substring(pos+10, s.length()-1);
    // Windows browsers include the full path on the client
    // But Linux/Unix and Mac browsers only send the filename
    // test if this is from a Windows browser
    pos = filepath.lastIndexOf("\\");
    if (pos != -1)
    filename = filepath.substring(pos + 1);
    else
    filename = filepath;
    private void setContentType(String s) {
    if (s==null)
    return;
    int pos = s.indexOf(": ");
    if (pos != -1)
    contentType = s.substring(pos+2, s.length());
    public void doUpload(HttpServletRequest request) throws IOException {
    ServletInputStream in = request.getInputStream();
    byte[] line = new byte[128];
    int i = in.readLine(line, 0, 128);
    if (i < 3)
    return;
    int boundaryLength = i - 2;
    String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character
    fields = new Hashtable();
    while (i != -1) {
    String newLine = new String(line, 0, i);
    if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {
    if (newLine.indexOf("filename=\"") != -1) {
    setFilename(new String(line, 0, i-2));
    if (filename==null)
    return;
    //this is the file content
    i = in.readLine(line, 0, 128);
    setContentType(new String(line, 0, i-2));
    i = in.readLine(line, 0, 128);
    // blank line
    i = in.readLine(line, 0, 128);
    newLine = new String(line, 0, i);
    PrintWriter pw = new PrintWriter(new BufferedWriter(new
    FileWriter((savePath==null? "" : savePath) + filename)));
    while (i != -1 && !newLine.startsWith(boundary)) {
    // the problem is the last line of the file content
    // contains the new line character.
    // So, we need to check if the current line is
    // the last line.
    i = in.readLine(line, 0, 128);
    if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
    && (new String(line, 0, i).startsWith(boundary)))
    pw.print(newLine.substring(0, newLine.length()-2));
    else
    pw.print(newLine);
    newLine = new String(line, 0, i);
    pw.close();
    else {
    //this is a field
    // get the field name
    int pos = newLine.indexOf("name=\"");
    String fieldName = newLine.substring(pos+6, newLine.length()-3);
    //System.out.println("fieldName:" + fieldName);
    // blank line
    i = in.readLine(line, 0, 128);
    i = in.readLine(line, 0, 128);
    newLine = new String(line, 0, i);
    StringBuffer fieldValue = new StringBuffer(128);
    while (i != -1 && !newLine.startsWith(boundary)) {
    // The last line of the field
    // contains the new line character.
    // So, we need to check if the current line is
    // the last line.
    i = in.readLine(line, 0, 128);
    if ((i==boundaryLength+2 || i==boundaryLength+4) // + 4 is eof
    && (new String(line, 0, i).startsWith(boundary)))
    fieldValue.append(newLine.substring(0, newLine.length()-2));
    else
    fieldValue.append(newLine);
    newLine = new String(line, 0, i);
    //System.out.println("fieldValue:" + fieldValue.toString());
    fields.put(fieldName, fieldValue.toString());
    i = in.readLine(line, 0, 128);
    } // end while
    This works fine and I can access the image name of the file by using the commands in my jsp code(on the resultant page of the new member form):
    <%@ page import="java.sql.*, com.idhcitip.*"%>
    <jsp:useBean id="TheBean" scope="page" class="com.idhcitip.FileUploadBean" />
    <%
    TheBean.doUpload(request);
    out.println("Filename:" + TheBean.getFilename());
    So I am wondering how can I then store this image into a text blob in the database?
    I found some code on the java.sun forum, but am not entirely sure how I am meant to use it?
    package com.idhcitip;
    import java.sql.*;
    import java.io.*;
    class BlobTest {
    public static void main(String args[]) {
    try {
    //File to be created. Original file is duke.gif.
    //DriverManager.registerDriver( new org.gjt.mm.mysql.Driver());
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    String host="localhost";
    String user="root";
    String pass="";
    String db="idhcitip";
    String conn;
    // create connection string
    conn = "jdbc:mysql://" + host + "/" + db + "?user=" + user + "&password=" +
    pass;
    // pass database parameters to JDBC driver
    Connection Conn = DriverManager.getConnection(conn);
    // query statement
    Statement SQLStatement = Conn.createStatement();
    /*PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobTest VALUES( ?, ? )" );
    pstmt.setString( 1, "photo1");
    File imageFile = new File("duke.gif");
    InputStream is = new FileInputStream(imageFile);
    pstmt.setBinaryStream( 2, is, (int)(imageFile.length()));
    pstmt.executeUpdate();
    PreparedStatement pstmt = Conn.prepareStatement("SELECT image FROM testblob WHERE Name = ?");
    pstmt.setString(1, args[0]);
    RandomAccessFile raf = new RandomAccessFile(args[0],"rw");
    ResultSet rs = pstmt.executeQuery();
    if(rs.next()) {
    Blob blob = rs.getBlob(1);
    int length = (int)blob.length();
    byte [] _blob = blob.getBytes(1, length);
    raf.write(_blob);
    System.out.println("Completed...");
    } catch(Exception e) {
    System.out.println(e);
    Once I have managed to store the file, I would just like people to be able to view each members profile and then to click on a link that will have their stored c.v.
    Thanks for a reply anyone

    You could do this one of two ways..
    using a prepaired statment, you could read in a byte array...
    String sql="INSERT INTO BlobTest VALUES( ? )";
    PreparedStatement ps=con.prepareStatement(sql);
    ps.setBytes(1, byte[]); //Your byte array buffer from your FileUploadBean
    ps.executeUpdate();or you could just use the input stream..
    String sql="INSERT INTO BlobTest VALUES( ? )";
    PreparedStatement ps=con.prepareStatement(sql);
    ps.setBinaryStream(1, InputStream, length); //You'll have to do some work to get length
    ps.executeUpdate();

  • File Upload with jsp & MultiPart

    Hi all,
    i've got a problem uploading a file from a multipart form.
    The file is correctly uploaded and i can open it, but I can't get the file name,
    In multipart.jsp fileName print out a null.
    Below the code. Can someone telle me where the error is?
    Thank's
    Kalvin
    this is the first page:
    prova.jsp:
    <form name="frmUp" action="multipart.jsp" method="POST" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit">
    </form>
    multipart.jsp:
    <%
    String fileName = request.getParameter("nomeFile");
    String pathFile = "/myPath/";
    InputStream is = request.getInputStream();
    out.println("File name:"+fileName+"<br>");
    UploadFile uf = new UploadFile(pathFile, fileName);
    if (uf.upload(is))
         out.println("OK<br>");
    else
         out.println("NO OK <br>");
    %>

    you have to get the filename from UploadFile object probably. You definitely can't get it from request cuz multipart forms are handled specially. If it saves the file properly, then it's probably assuming a null filename means to use the name as it was uploaded, but UploadFile should be able to give you a File object for where the file was put.

  • Using java files with JSP

    Ok, so im pretty new to this JSP lark and have a question.
    I have Java Classes resting in .java files, i need to know how
    do i link these files to my .jsp page so that the classes/variable etc.
    declared with the java files are recognised when they are come
    across in the .jsp file.
    I dont know if I have explained that properly.

    Just include this statement at the top of your jsp:
    <%@page import="yourpackage.yourclass"%>
    The .java files should of course be compiled into .class files prior to using (and you don't include the extension when importing).

  • Prob in  working with jsp 2.0 tags fil

    hi all
    i am facing a prob working with jsp 2.0 tags files and hope to receive a possitive responce from your good self:-
    <p>
    how could i create a instance of a user defined class in a tags files .
    <p>eg.
    <tb:firsttag tableName="customer" className="createtable" packagename="package1">
    <BR>
    </tb:firsttag>
    what code i have to write in tag file to create a object of class createtable </br>
    thanks in advance, waiting for ur cooperation

    I'm not sure I understand your question, but...
    If you want to create a custom tag that will contain a body (data between the start and end tags) you will extend BodyTagSupport.
    HTH.

  • Generaating new doc file with jsp servlet.

    Hi friends,
    I developed an application with JSP
    In that i need a data to be fetched nd write in .doc file.
    I mean I want to create new word file nd get my data in that
    like reports generation.
    How can i make this.
    help me pls

    .doc file: I don't think there is any reporting tool that creates .doc. You can create .rtf files with Oracle Reports and many other tools.

  • How to read *.txt files with JSP?

    I have to make a homepage that searches for information on a text file.
    My text file is described below.
    username=Hanako Sony
    cpname=Sony Corporation
    cpcode=500100
    So, if the user inputs "username", then "Hanako Sony" should be returned. If the user inputs "cpname", then "Sony Corporation" should be returned and so on.
    Can anyone help me with this? Can this be done with JSP?
    Thanks,
    Rob

    Try this,
    <%@ page import="java.io.*,java.util.*" %>
    <%
    RandomAccessFile raf = new RandomAccessFile("../webapps/test/jsp/Info.txt","r");
    String qInfo = request.getParameter("qInfo");
    String tInfo="";
    if(qInfo != null) {
         String line="";
         while((line = raf.readLine()) != null) {
              StringTokenizer st = new StringTokenizer(line,"=");
              if(st.hasMoreTokens()) {
                   if(st.nextToken().equalsIgnoreCase(qInfo))
                        tInfo = st.nextToken();
         if(tInfo.equals("")) tInfo="Property Not found ???";
    } else {
         qInfo="";
    %>
    <form name=myform action="" method="get">
    <table><tr>
    <td>What do you want : </td><td><input type = text name="qInfo" value="<%=qInfo%>"></td></tr>
    <tr><td>Here is the information : </td><td><input type = text name="tInfo" value="<%=tInfo%>"></td></tr>
    <tr><td><input type="submit" name"sub"></td></tr>
    </table>
    </form>Here info.txt is your text file. Use the relative path accordingly.
    Hope this helps.
    Sudha

  • Sign on problems within Elements 10; plus cannot backup writing files error with file catalog.pse10db.  No indication what the problem is.  How do I get adobe help with these problems?

    Sign on problems within Elements 10; plus cannot backup, writing files error with file catalog.pse10db.  No indication what the problem is.  How do I get adobe help with these problems?

    Sign on problems within Elements 10; plus cannot backup, writing files error with file catalog.pse10db.  No indication what the problem is.  How do I get adobe help with these problems?

  • Writing XML file from a jsp page

    how can i write a xml file from my jsp and store the values and after sometime, for example when the user clicks on the submit button, i check the values from xml file and compare those values from the data base.
    it means both writing and reading xml file from a jsp page...
    urgent help needed......thanks

    You need some API like XSL or JDOM to read data from/to XML file
    you can get a best tutorial from
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0518-jdom.html
    and
    http://www.javaworld.com/javaworld/jw-07-2000/jw-0728-jdom2.html
    after reading both articals you will be able to do both the tasks

  • Writing Files Access Denied JSP+IAS+W2K

    Hi.
    I'm trying to write a file from a JSP to a mapped share unit between a W2K Server (i: as mapped unit) with IAS and a W2K Server with Oracle (c:\loadDir as deposit unit which is mapped by the IAS server) . I already bring all security grants but when the JSP tries to write to the I: unit it answer "access denied".
    both machines are in the same workgroup but not inside a domain.
    tks for the help.

    I finally find the solutions in a TAR published in metalink. The problem is that the service of IAS runs as a user SYSTEM, this user don't have permissions on the other machine to write.
    The solution is to make the service to start as another user that as the enough permissions to write.
    hope this help some one else.

  • JSP File Writing

    hai all
    i am trying to write some data into file in JSP
    my web structure is
    /jsp
    /jsp/others
    my jsp file is in .jsp i want to create a file called Rajesh.txt in /jsp/others/Rajesh.txt
    when i write
    rintWriter fileObject = new PrintWriter(new FileWriter("./others/Rajesh.txt",false));
    fileObject.write("Hello World");
    its throwing .\others\Rajesh.txt (The system cannot find the path specified) Exception
    please help me
    Rajesh

    error once more for code
              PrintWriter fileObject = new PrintWriter(new FileWriter(getServletContext().getRealPath("others/Rajesh.txt"),false));
    C:\JavaWorld\Tomcat4.1\bin\..\webapps\finalmpc\others\Rajesh.txt (The system cannot find the path specified)
    why ??

  • How to generate a xml file with JSP?

    Hi,
    I want to dynamically generate maths formula in my web page. I think MathMl is a good choice. However, it needs xml file. I try to use JSP to generate the
    content of the xml file. However, it doesn't work. What should I do?
    Best regards.

    Hi,
    Thanks a lot for your replies. I used to write JSP to present quiz fetching from a database. To use MathML, xml file has to be used. I've tried to copy the content of the xml file to a jsp file and let the brower to display it. However, it doesn't work. I view the content of the page displayed by the brower. I simply contain nothing. So what it's the most convenience way to present the MathML dynamically.
    Best regards.
    From hoifo

  • File writing permissions??

    is there any file writing permissions in jsp?
    i can create folders with my code on my localhost Tomcat 5.5.
    but now i have a webhost which has Tomcat 5.0...with my same jsp code i can see the content of my folders but cannot create any new folders under wwwroot or somewhere else on my webhost...
    so i am thinking if it is related with permissions or something like that?please show me a way
    thanks
    Burak

    my host admin responded;
    Hi,
    We can enable write permission, but this will put you in high security risk in tomcat shared hosting, as any other user also from his jsp/servlet script can write anything into your directory or delete file.
    Now what you think?what i want to do is i have a photo album site...users can create their own folders and upload their photo albums...but this users' main folder must be somewhere in a protected area that users musnt directly link to this photos...like before wwwroot or after WEB-INF folder...where can it be?
    please help me in this subject..need really help..
    thanks

Maybe you are looking for

  • Copying songs from iTunes to a CD to play in car

    I am trying to burn a playlist of songs which I purchased in iTunes onto a CD so that I can play it in my car. I have tried twice, but after had two failed attempts. Got an error message at the end : Disc failed to burn ..Error 4450. Can someone plea

  • MS K9N4-SLI---Win 7 Support??

    Yeah, I've got this old board. It's been a true workhorse for me with an AMD 64X2 5400+ processor.  Does MSI support this board for win 7? Currently running tried and true XP Home and have no choice but to update to Win 7 because of ending support by

  • In app purchase via iMob app for $99.99

    I have read a lot of parents feeling scammed by in app purchases made by their own kids or young relatives.  I am writing because this happened to me as well when my 7 year old made a virtual purchase through an app that was downloaded for free.  I a

  • Exsternal harddrive drops out, when using adobe premiere pro cs5. Cant load projects. any one had this problem or the answer to it?

    I have two WD external hard drives that i keep all my video files, music and adobe premiere pro cs5 projects on. Up until 2 days ago they were working perfect, now they drop out when i try and load my projects from them, or watch a movie from them. t

  • 10.5.7 won't restart after update

    I have tried updating an G4 iBook running 10.5.3 to 10.5.7 through the software update in the Apple Menu. The download took a long time but was apparently successful. When I restarted the machine the progress bar hung up during the 'configuring insta