File writing serialization

I have to build a web application using servlet and jsp. The user should edit some
text file (maybe displaying the file fields in a HTML form).
I need some suggestions about implementing the synchronization on file writing (since different
users should try to save the same file simultaneously).
Do some standard pattern exist about this feature ?
I suppose to do that using a java bean whith application scope shared by the jsp pages. In this bean
I will implement all write methods using synchronized.
Any suggestions ?
Thanks in advance,
Mauro.

well, if you have a single method which does the actual file writing, then you make that method synchronized and you'll have no problems. You can build up the data to write in some object at any time and pass that to that method.
However, that's still going to present problems when users actually modify the file at the same time. Why does every user have to share 1 file?

Similar Messages

  • Why when I'm trying to reinstall my OS, Tiger 10.4, at 56% at files writing, it shuts off?

    Please someone, help me,
    Why when I'm trying to reinstall my OS, Tiger 10.4, at 56% of the installation, at files writing, it keeps on shutting off?

    Does it feel extra hot on top?
    Are you reinstalling because you had several problems? If so what were they?
    "Try Disk Utility
    1. Insert the Mac OS X Install disc, then restart the computer while holding the C key.
    2. When your computer finishes starting up from the disc, choose Disk Utility from the Installer menu at top of the screen. (In Mac OS X 10.4 or later, you must select your language first.)
    *Important: Do not click Continue in the first screen of the Installer. If you do, you must restart from the disc again to access Disk Utility.*
    3. Click the First Aid tab.
    4. Select your Mac OS X volume.
    5. Click Repair Disk, (not Repair Permissions). Disk Utility checks and repairs the disk."
    http://docs.info.apple.com/article.html?artnum=106214

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

  • 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

  • Does UTL_FIL utility supports file writing in to remote Host ??

    Hi,
    I am checking the possibility with UTL_FIL utility whether supports file writing in to remote Host. My database is on different server from UNIX server but i want to make use of Oracle directory objects or UTL_FILES functions to be able to write files directly from Oracle to remote UNIX server.
    Is this possible ?
    Thanks
    Anand

    UTL_FILE, and any other PL/SQL package running on the database server, can only access objects that the database server has access to. Unless the remote Unix server's file system is mounted from the Oracle server's file system, UTL_FILE would be unable to create a file there.
    Now, there may well be alternateives. For example, you could generate the file locally and FTP the file to the remote Unix server, assuming the remote Unix server is running a FTP server.
    Justin

  • What is the best way to store data to a file? Serialization?

    FYI: I am some what of a novice programer. I have almost finished my degree but everything I know about Java is self taught (never taken a course in java). Any way here is my question.
    So I have an example program that I have created. It basically just has three textpanes which also have the ability to contain images. Now I would like to learn how to store data to a file for later retrieval and decided to use a program such as this as an example. I am not sure if I should use the serialization API that java has or some other means such as XML. If I used XML I was not sure how to store the image data that would be contained in the text panes. I figured serialization would take care of that if I just serialized my main class and then restored it. So That is that I tried first. Is this a good direction to go?
    The problem I am having is that I cant seem to get the serialization to work the way I need it to. I am not sure what I am doing wrong because I have read many tutorials and looked at allot of example code but still dont understand. The tutorial I looked at most is [this one at IBM.|http://java.sun.com/developer/technicalArticles/Programming/serialization/]
    The eclipse project folder for my example program can be found here:
    [http://startoftext.com/stuff/myMenuExp/]
    zipped version:
    [http://startoftext.com/stuff/myMenuExp.zip]
    The main class is mainwindow.java. I know the source is kinda dirty. Any comments are welcome but I am most interested in how to solve this serialization problem. Thanks
    -James

    DrClap wrote:
    What will the nature of the data be? Just a handful of strings? A bunch of objects of different types reflecting the current state of your program to great depth and complexity? Something else?The data will be what is contained in three text panes. Each text pane containing rich text and images. For an example take a look at the example program in my first post.
    How will the data be used? Just write it out when the app shuts down, and read it all back in when it starts up? Do you need to query or search for specific subsets of the data? Is there any value in the stored form of the data being human-readable?Basically the data will need to be saved when the application shuts down or when the user selects save from the file menu. The data will be restored when the user opens the file from the file menu. It would be nice if the stored data is human readable but its not of primary importance.
    How often will the data be written and read? How many reads/writes/bytes/etc. per second/minute? Not often. Just a simple open and save from the file menu.
    How large could the data conceivably get?It will probably be a few paragraphs of formated text and less then a dozen images per text pane.
    Will reading and writing of the data need to occur concurrently?no.
    Do you need to add new data to the storage as your app goes along, or just replace what's there with the most current state?Replace with the most current state of the data.
    If it's a simple read once at startup, write once at shutdown, overwriting the previous data, read only by your app, not by humans, then serialization via ObjectInput/OutputStream is probably the way to go. If there are other requirements, you may want to go with XML serialization, a DB, or some other solution.Thanks for the information. Serialization sounds like the way to go. Even if I end up using XML serialization in the end it would still be of interest to me to learn how to use serialization without xml.
    I was trying to go with using serialization in be beginning but I cant seem to get it to work. Would you be willing to take a look at my example program. I attempted to implement serialization but it does not seem to work. Could you take a look and see what I am doing wrong. At this point I am stuck as i cant seem to get serialization to work.
    I am going to go ahead and mark this thread as answered because I think I already got most of the information I was looking for except what I am doing wrong with my attempt as serialization.
    Thank you jverd for your time.

  • Binary File, ArrayList, Serialization

    So I'm making a program that will be writing to a binary file. When the program first starts it checks if the binary file is in the directory the program is in, if it is not the file is written to the hard drive. This program will be using an ArrayList to manage objects and the objects will be serialized, but what about the ArrayList? Is it serialized, written to the file, or what? If it is written to the file how would I do that?

    Er I was following an online tutorial on it..Not
    really my code just filling in stuff. As you can
    tell, I'm a newbie in Java..Got any ideas on how to
    serialize it?I would really like to know what settingsHash is...
    ArrayList mylist = new ArrayList();
    FileOutputStream fileOut = new FileOutputStream(MyFile);
    ///fileOut = new FileOutputStream(MyFile); commented out the redundancy
    ObjectOutputStream oos = new  ObjectOutputStream(fileOut);
    oos.writeObject(myList);// hopefully serializes your ArrayList to the file
    oos.close();// please to close streams after using

  • File Writing - Missing some files without any error

    I am executing the following code:
    String message = XMLHelper.getDocumentXML(_doc);
         File outFile = getFile();
         RandomAccessFile raf = new RandomAccessFile(outFile, "rw");
         FileChannel channel = raf.getChannel();
         ByteBuffer buf = ByteBuffer.allocateDirect(19600);
         buf.clear();
         buf.put(message.getBytes());
         buf.flip();
         channel.write(buf);
         channel.close();
         raf.close();
    This code is in a loop and it must write a lot of files. I am trying with 426 but thje problem i have is that many times i do get 425 files insted of 426 or some other times i do get 425 files. No error or exception is thrown. Other times id do get my 426 files.
    The problem increase when i process like 50000 files, the quantity it is supposed to treat.
    Please can any body tell me what happen with the missing files? How can i detect what is happening?
    Thank you very much to any one who can help me with this extrange error

    Hard to tell based on the info you supplied. How are you generating filenames? Are you accidently writing over an existing ouput file? Can you post more code, speciifcally the loop code around the code below?

  • Problem in creating New line in --File writing(Urgent)

    Hi all
    I am facing a tipical problem.
    I am writing a Text file using FileWriter and i am using "\n" for writing a new line,
    but when i open notepad all are falling on a single line with a special char
    (if i open the text file in some other editor vie wis very fine)
    C-0-1@C-1-0@ C-2-1
    @ is where i am writing new line.
    but this king of writing is not supported by my third party tool to which i am sending the text file
    as parameter..
    Kindly any one provide me a solution.
    Bye

    newlines differ between windows and linux/unix. Windows' new line character is somthing like "\n\m" where linux uses "/n". So to keep your program platform independent I would suggest using System.getProperty("line.separator") so your code might look like:
    String s = "C-0-1" + System.getProperty("line.separator") + "C-1-0" + System.getProperty("line.separator") + "C-2-1";
    //then write the string to the filethis will give you the appropriate newline character for the platform your program runs on.

  • Problem with file writing

    Hello, I have a problem with writing a file. My code is very simple..it takes a line from one file, a line from a second file, combines them, and writes them into the third file. However, the program never gets past the point where it creates the output file. Any help is appreciated.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MergeFiles extends JApplet implements ActionListener
        private final String filename = "mergedfiles.txt";
        BufferedReader f1in, f2in;
        FileOutputStream outputstream;
        JTextField f1f = new JTextField("file1.txt", 20);
        JTextField f2f = new JTextField("file2.txt", 20);
        String F1text, F2text, F3text;
        JLabel title = new JLabel("Merge files program! Press enter to merge!");
        JButton merge = new JButton("MERGE! MERGE! MERGE!");
        JLabel labelone = new JLabel("File one");
        JLabel labeltwo = new JLabel("File two");
        Container con = getContentPane();
        JPanel pane = new JPanel();
        GridBagConstraints c = new GridBagConstraints();
        public void makedisplay()
            Insets i = new Insets(10, 10, 10, 10);
            pane.setLayout(new GridBagLayout());
            pane.setBackground(Color.green);
            con.setBackground(Color.green);
            con.add(pane, BorderLayout.CENTER);
            con.add(title, BorderLayout.NORTH);
            c.weightx = 0;
            c.insets = i;
            c.gridy = 0;
            c.gridx = 0;
            pane.add(labelone, c);
            c.gridx = 1;
            pane.add(labeltwo, c);
            c.gridx = 0;
            c.gridy = 1;
            c.ipadx = 50;
            pane.add(f1f, c);
            c.gridx = 1;
            pane.add(f2f, c);
            c.gridx = 0;
            c.gridy = 2;
            c.gridwidth = 3;
            c.ipadx = 0;
            pane.add(merge, c);
        public void init()
            makedisplay();
            merge.addActionListener(this);
        public void actionPerformed(ActionEvent e)
            openfiles();
            File f = new File("H://mergefiles//mergedfile.txt");
            try {
                title.setText("AAA");
                BufferedWriter out = new BufferedWriter(new FileWriter(f));
                F1text = f1in.readLine();
                F2text = f2in.readLine();
                title.setText("BBB");
                F3text = "" + F1text + F2text;
                out.write("" + F3text);
                f1in.close();
                f2in.close();
                out.close();
             catch (IOException ex)
        public void openfiles()
            try
                BufferedReader f1in = new BufferedReader(new FileReader(f1f.getText()));
                title.setText("file one opened");
            catch (FileNotFoundException e)
                title.setText("File one not found!");
            try
                BufferedReader f2in = new BufferedReader(new FileReader(f2f.getText()));
                title.setText("File two opened");
            catch (FileNotFoundException e)
                title.setText("File two not found!");
    }

    Nevermind, I've fixed the problem...for some reason you can't use the writer with an applet. I've written some new code that works:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MergeFiles2
        static String F1L = "", F2L = "";
        static File file1 = new File("H://mergefiles//file1.txt");
        static File file2 = new File("H://mergefiles//file2.txt");
        public static void main(String[] args) throws IOException
            PrintWriter out = new PrintWriter(new FileWriter("file3.txt"));
            BufferedReader f1in = new BufferedReader(new FileReader(file1));
            BufferedReader f2in = new BufferedReader(new FileReader(file2));
            while (F1L != null)
                F1L = f1in.readLine();
                if (F1L != null)
                    out.println(F1L);
            while (F2L != null)
                F2L = f2in.readLine();
                if (F2L != null)
                    out.println(F2L);
            out.close();
    }

  • Applet file writing without permission

    Is it possible for an applet to write a text or html document to be displayed in a browser without needing to grant it permissions?

    I experimented with writing a file and naming the file to the directory that the applet's in using getCodeBase(), but that didn't work. I've been looking into writing directly to a browser, but that's kind of ugly, and it looks like you have to play with system paths and what-not in order to talk to javascript, so I ruled that out. Any help is appreciated.

  • Synchronized File Writing

    Hi,
    I have a written a Java Program which Splits any File into two Parts. These parts can again later be rejoined to restore the Original File.
    This is how Splitting Operation is performed
    1. Read the SourceFile into Array of Bytes
    2. Open two FileOutputStreams and Write these Bytes, half of it in each stream. This is Done using a Thread for Each stream, Obviously to save time.
    3. Now i have two Files which contain Bytes for Original File.
    Now in Restoring Operation:
    1. Read the two Files(split using above technique) and store in Byte Arrays.
    2. Open the FileOutputStream to a File and write the Above byte Arrays ONE BY ONE into this Stream.
    Please note that i had to write Bytes from two byte arrays in the Order i had read it.
    Which means to say that i first have to write From First Byte Array, wait for it to finish it and than write from Second Byte Array. I cannot start Threads for Writing Bcoz the Target File is Same. Also, i wouldn't know where to start writing the bytes from Second Byte Array in the target File since, the First Thread may still be performing the Write Operation from the First Byte Array
    If i had been writing a C program, this would be fairly easy since i have File Pointers. I can use two programs and use fseek() operation to Know exactly where to start writing from second set of Byte Array.
    Please give ur suggestion to above problem. How can i simulate File Pointer operations of C in Java.
    I hope i am Clear in describing the Problem. If not, then please let me know......and Thnx for u Patience

    try not to cross post.
    http://forum.java.sun.com/thread.jsp?forum=4&thread=165965&start=0&range=30#501577

  • Plain file writing vs. Object writing

    Hi,
    I've a question about the use of object serialization when it comes to file io. Suppose I've written a binary tree datastructure, which is a pretty complex one. I've filled the tree with many object and now I want to be able to save the tree for later use. I could design some file format for the tree. But I could also use object serialization and write the whole tree object to file using the ObjectOutputStream. This makes it a lot easier.
    I also could write a simple preferences object (a static class with static Strings, which define my preferences) to a file, without saving the preferences using some file format.
    Now my question is: is object serialization meant for these types of things? Is this a good way of using it, or, for example, are the files going to be larger than necessary?
    Thank you!
    Jeroen

    Serialization will give you a pretty compact file. Not neccesarily the smallest possible file, but you would need to spend some time and effort creating aformat that yields smaller files, and there's not much space to gain this way.
    Serialization is fine when you never want to read the file with a program that's not written in java. Because reading a serialized file using a non-java program would mean implementing the code to parse and understand the encdings for the java object format and the java primitive types.
    Serialization pretty much prevents you from doing meaningsfull inspection of your data using less, grep or a text editor. If you want to be able to do this, then use a custom format that's built for readibily with such tools. It can still be pretty compact.

  • Save a "component of a JFrame to a file.  serialization

    hi there
    i read something about serialization and using the transient the example on there just using one non-serializable object . but in my case the object is going to be saved which contains : contains: String, double, Graphic, some DataSet.... etc.
    actually , i am trying to save a 'component' of a JFrame to a file, the component is a graph........... then i could load the file to do something configration (etc change the name of the graph "String", change the color....).
    but when i use the wirteObject method :
    out.writeObject(component);
    I got the NotSerializableException. I know all the objects have to be serializable in order to use the writeObject method also i know some of the component's objects aren't serialzable but it might contains a 100 of different objects??????...
    as i understand, i have to override the readObject and writeObject methods to make alll the object to serialization????? so how could i do that??? there is not just one or two objects..
    pls help
    thanks in advance

    Take a look at this stuff and see if it helps to solve your problem:
    http://java.sun.com/products/jfc/tsc/articles/persistence4/index.html
    It provides some classes, etc. on how to persist your object graph as an XML file, and then read it back in, etc.

  • File Writing Issue :-(

    Hello Guys,
    Im trying to write into a file from a InputStream..For which the code is as followspublic void saveFile(String filename,InputStream inpStr)
    try{
    InputStreamReader stream=new InputStreamReader(inpStr,"SJIS");     
    File tobSavedFile=new File(filename);
    FileOutputStream fstr=new FileOutputStream(tobSavedFile);
    while (true){
        int d=stream.read();
        if (d==-1) break;
        else
         fstr.write(d);
    catch(Exception me){
       me.printStackTrace();
    }This code works fine when i pass a Text file as inputstream,But it doesnt work good when i pass a GIF or JPG or ZIP file in inputStream...
    For example when i passed a file as GIF which was 1.45KB it resulted in creation of GIF file of just 1.34KB..
    Why is this??can any one help me..
    Thanks a lot for your patience.
    Regds,
    Gokul

    Don't use an InputStreamReader around your InputStream, it's trying to do text conversion and not supposed to be used for binary data.

Maybe you are looking for

  • QuickTime fatal error during uninstalling

    I'm trying to install itunes on my 3 year old Gateway desktop at home so I can sync my iphone to it and not to my work laptop that needs to be turned in. When trying to install itunes it gives me a fatal error message when trying to update QuickTime.

  • Arch linux on ubuntu?

    I was always wondering, why is there an arch linux sub-forum on the ubuntu forum?

  • MessageExpiredException: Sync application request expired..

    Hi, we are calling a SOAP HTTP AXIS receiver (web service) HTTP. Sometimes the service providers request takes 3 minutes to reply and we get  the following exception : com.sap.engine.interfaces.messaging.api.exception.MessageExpiredException: Sync ap

  • Tax procudures TAXINN & TAXINJ

    Hi Gurus, I am configuring CIN in my IDES client. I have activated CIN easy access screen by adding SAP_CIN in user parameters. Started confiuring CIN in IMG. I am at the stage of assigning Tax calculation procedure to country. Logistics general->Tax

  • Moving from one device to another

    MY iPod got water in it and won't come back on. I purchased another one.  How do I use iCloud to move my stuff off my old iPod to my new iPod?