Write to a file using several threads

Hello,
I'm trying to implement a writing procedure into a file using several different threads. The idea I have is to make each thread to write in a different place in the file. In your opinion is there a possibility of some incoherence.
Regards,
Anton
Edited by: anton_tonev on Oct 22, 2007 3:28 AM

At this moment I can't give a source code example because I'm writing it :) and I'm trying to see the cases where I may have some problems.
But my idea is to access the file at any time and to write into it with differenent threads in a differenet places in this file. In fact the problem I'm trying to solve is :
I have a objects called Data that are generated by some other thread independent of my application. This thread puts the Data objects in some kind if buffer. When the buffer is full, I'm creating a few threads fo every object Data in this buffer (the data objects in its own is some collection of floats and doubles) So I'm trying to position the new created threads over the file but in different places and then make them write the data collected in the object Data.
To position de threads over the file, I'm accessing it by some synchronous method to undestand where it can write in this file and the writing is not synchronous because I'm trying to calculate the exact place and number of bytes of writing and in this way to avoid (may be) the eventuality of errors.
Regards,
Anton

Similar Messages

  • How Do I write an XML file using Java?

    Hello there!! to everyone reading my post.
    I have this project I need to do, and I have no clue where to start, I was wondering if you guys could help me out.
    I need to know how to write an XML file using a Java Program, but without using a Third party library.... just using java native APIs.
    I will probably take the values to construct the file from a form.
    I will certainly appreciate if you could post some sample code for me.
    Thank you very much in advance..

    Hello there!,
    I have some doubts about the Tutorial I am currently reading. correct me If I'm wrong, but the section "Write a simple XML file" teaches you how to do so using a text editor. I need to create my XML file from a running Java Program written by myself, that takes the values to build it from some variables.
    If I'm totally wrong about what I'm saying, could you please point me to where I can find the information of how to do what I'm asking for, inside the tutorial.
    Thank you very much,...
    sincerely.

  • Write in a file using FileConnection

    Hello, I have to write in a file using the FileConnection API (JME).
    So far, I could write it, but I could not find out how to append in the file.
    Here is the code:
    FileConnection fc = (FileConnection)
    Connector.open("file:///test.txt");
    OutputStream os =  fc.Open(OutputStream);
    OutputStreamWriter osw = new OutputStreamWriter(os);
    osw.write("test");
    How can I add new data at the end of the file?

    Well, I really can't find a method I could use, so I read the file and put it in a buffer, then I write it all.
    I will let the code for anyone who needs:
    +try {+
    FileConnection fc = (FileConnection) Connector.open("file:///j9/test.txt");
    if (!fc.exists())
    fc.create();
    InputStream is = fc.openInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    +char[] c = new char[(int) fc.fileSize()];+
    isr.read(c);
    OutputStream os = fc.openOutputStream();
    String str = textField.getString() ',' + textField1.getString() + '\n';+
    os.write(new String(c).getBytes());
    os.write(str.getBytes());
    os.close();
    is.close();
    isr.close();
    fc.close();
    stringItem1.setText("It works");
    +}+
    +catch (Exception ex) {+
    stringItem1.setText("It doesn't work");
    +}+

  • Write to a file using a system variable in the path

    I got an error when I used the following command to write a file
    OdiOutFile "-FILE=<%=System.getProperty("LOG")%>\test.log" -APPEND "-CHARSET_ENCODING=ISO8859_1" "-XROW_SEP=0D0A"
    The "LOG' is an environment variable.
    The error is
    java.lang.Exception: Oracle Data Integrator Function does not exist
    It looks like ODI treat System.getProperty as ODI function instead of java method. I use SUNOPSIS API as technology in the command

    At this moment I can't give a source code example because I'm writing it :) and I'm trying to see the cases where I may have some problems.
    But my idea is to access the file at any time and to write into it with differenent threads in a differenet places in this file. In fact the problem I'm trying to solve is :
    I have a objects called Data that are generated by some other thread independent of my application. This thread puts the Data objects in some kind if buffer. When the buffer is full, I'm creating a few threads fo every object Data in this buffer (the data objects in its own is some collection of floats and doubles) So I'm trying to position the new created threads over the file but in different places and then make them write the data collected in the object Data.
    To position de threads over the file, I'm accessing it by some synchronous method to undestand where it can write in this file and the writing is not synchronous because I'm trying to calculate the exact place and number of bytes of writing and in this way to avoid (may be) the eventuality of errors.
    Regards,
    Anton

  • How to write as XML file using java 1.5

    hi all,
    i am trying to create an XML file using java 1.5. I took a XML creating java file which was working with java 1.4 and ported same file into java 1.5 with changes according to the SAX and DOM implmentation in java 1.5 and tried to compile. But while writing as a file it throws error "cannot find the symbol."
    can any body help me out to solve this issue.......
    thankx in advance
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.NamedNodeMap;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.xml.sax.DocumentHandler;
    import org.xml.sax.InputSource;
    import org.xml.sax.helpers.ParserFactory;
    import java.io.*;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                   
                   dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();                   
    Document xmlDoc =  db.newDocument();
    // this creates the xml document ref
    // parent node reference
    Element rootnd = (Element) xmlDoc.createElement("ALL_TABLES");
    // root node
    xmlDoc.appendChild(rootnd);
    Element rownd = (Element) xmlDoc.createElement("ROW");
    rootnd.appendChild(rownd);
    Element statusnd = (Element) xmlDoc.createElement("FILE_STATUS");
    rownd.appendChild(statusnd);
    statusnd.appendChild(xmlDoc.createTextNode("Y")
    FileOutputStream outpt = new FileOutputStream(outdir + "//forbranch.xml");
    Writer outf = new OutputStreamWriter(outpt, "UTF-8");
    //error is occuring here Since write method is not available in the Document class
    xmlDoc.write(outf);
    outf.flush();

    Hi,
    when I look in the JDK1.4.2 specification I don't see any write method in the Document interface.
    However, your solution is the Transformer class. There you transform your DOM tree into any output you need. Your code sould look something like this:     TransformerFactory tf = TransformerFactory.newInstance();
         // set all necessary features for your transformer -> see OutputKeys
         Transformer t = tf.newTransformer();
         t.transform(new DOMSource(xmlDoc), new StreamResult(file));Then you have your XML file stored in the file system.
    Hope it helps.

  • Read and write into csv file using procedure

    I would like to read a particular column value from csv file(which will have many columns) using procedure and for that value I have to retrieve some more values from database table and have to append into same csv file.
    can someone help me?
    Thanks
    Edited by: 1002478 on Apr 25, 2013 5:52 AM
    Edited by: 1002478 on Apr 25, 2013 5:55 AM

    1002478 wrote:
    thanks for your reply.
    Using UTL_FILE i'm able to read csv file. I'm stuck up in appending some more columns to same csvYou'll struggle to append data to an existing CSV.
    You'd be better to read the data from one CSV, and create another CSV using that data, and the extra data you want, and then when finished, delete the original file and rename the new file to the old filename.
    You should be able to do that using External Tables to read the source file (easier than using UTL_FILE) and UTL_FILE to write the new file.

  • Write to existing file using servlets

    Every time I try to read an existing file using my current set of servlets, I get "File cannot be found". I don't understand what the problem is because I'm using the exact same location as the code where I read the document. Is there something else I'm missing? I've tried countless methods of writing, each will compile and such, but all give me the same result (IE nothing). Here's how my horrific code looks right now. Much was taken from the previous code that checks the passwords file.
    Technically, it compiles and runs, but I get "java.io.FileNotFoundException: \WEB-INF\passwords (The system cannot find the path specified)" in the output. The file IS THERE and can be read in my password checking servlet without a problem...
    package hw3Pack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    public class passCheck extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
            response.setContentType("text/html");
            HttpSession session = request.getSession(true);
            PrintWriter out = response.getWriter();
            try {
                    String filename = "/WEB-INF/passwords";
                    String email = request.getParameter("email");
                    String password = request.getParameter("password");
                    String remember = request.getParameter("remember");
                    ServletContext context = getServletContext();
              FileOutputStream fos = new FileOutputStream(filename);
                    InputStream is = context.getResourceAsStream(filename);
              if (!is.equals(null)) {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader reader = new BufferedReader(isr);
                   String text = "";
                            } // if (is != null)
                    else {
                    } // else (password not blank)
            finally {
                out.close();
            } // finally
    }

    OK... I feel a bit dumb now... This code was working earlier (the writing part) and now it's not working since I added in the username check portion. It should be essentially complete at this point, I just need to figure out why it no longer writes the file. Any clues or insights?
    I'm about to add a password checker (confirm both passwords entered on registration form are equal) Lets hope I don't mess more up...
    package hw3Pack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    import java.net.*;
    public class regComplete extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
            response.setContentType("text/html");
            HttpSession session = request.getSession(true);
            PrintWriter out = response.getWriter();
            boolean clear = true;
            try {
                    String email = request.getParameter("email");
                    String password = request.getParameter("password");
                    out.println(email +" and " + password);
                    String filename = "/WEB-INF/passwords";
                    ServletContext context = getServletContext();
                    InputStream is = context.getResourceAsStream(filename);
              if (!is.equals(null)) {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader reader = new BufferedReader(isr);
                   String text = "";
                            while ((text = reader.readLine()) != null) {              
                                    StringTokenizer st = new StringTokenizer(text, "," );
                                    String getEmail = st.nextToken();
                                    String getPass = st.nextToken();
                                            if (email.equals(getEmail) && !email.equals(null)) {
                                                    clear = false;
                                                    out.println("I'm sorry but that email address is in use.  Please try again.");
                                            } else {
                                            //do nothing
                    if (clear==true) {
                        File file = new File("/WEB-INF/passwords");
                        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
                        out.println("going");
                        writer.append("\r\n" +email +"," +password);
                        out.println("Writing");
                        writer.close();
                        } else {
                } // try
            finally {
                out.close();
                } // finally
      }

  • Can't write to a file using File class

    hi every body
    I wanna write into a file for logging purpose, but I always
    got an error when I write to the file ...
    the code is:
    if(!logFile.isOpen)
    logFile.open("text", "write")
    var date = new Date();
    if(logFile.canWrite){
    trace(">> I will write ...");
    var message = "TIME >> " + date.getDate().toString() +
    " : ERROR CODE >> " + infoObject.code + " : LINE NO >>
    " + infoObject.lineno.toString();
    logFile.write(message);
    logFile.flush();
    logFile.close();
    I got an error says: File operation writeln failed
    and also may say: File operation flush failed
    thanx

    First off, don't use finalize(). It is never guaranteed to actually run.
    Just add a cleanup() method to your Account class that flushes and closes the writer; and call it before you exit main().
    Now, as for your Date problem
    java.util.Date certainly does have a no-args constructor.
    java.sql.Date does not.
    Make sure you aren't getting a name collision. (Hint: If you're doing import java.foo.* Stop Doing That. just import the classes you need)

  • Write an excel file using File adapter

    Hi,
    I have a scenario in which i have to write an excel file in the target system.
    I tried creating a tab delimited file conversion and just named the file as .xls.
    When i saw the output file it did look like a excel but a report that i have written to read a excel file cant read it.
    The report says 0 records found. It works for other excel sheets that are created manually.
    So will this method noit work for creating excel files?
    Is using the jexcel api the only option for this?

    Have u had a chance to see this excellent blog by shabarish...
    chekc this
    /people/shabarish.vijayakumar/blog/2009/04/05/excel-files--how-to-handle-them-in-sap-xipi-the-alternatives
    http://wiki.sdn.sap.com/wiki/display/XI/CODE-CreateanExcelFileviatheJExcel+API

  • How to "print" to a PDF file using several templates?

    I have Adobe Acrobat X Professional.
    Now I want to export my documents (letters, bids, invoices etc. from my ERP) to PDF files using the Adobe PDF printer driver using different layout templates for example: we have two different letterheads (already PDF files) and some of the documents have to be exported/merged onto the first, and others have to be exported/merged onto the second letterhead.
    Are there any options on how to select different templates in the Adobe PDF printer.
    And if not, are there any solutions how to integrate this functionality into Adobe PDF printer.
    Any help is greatly appreciated
    Cheers,
    Harald

    ok, that's right. i also can use the add layer command to create the text over the letterhead.
    but this is impractical. the users should be able to export the document using the desired template.
    i need a superimpose feature or something like that for the pdf writer. hopefully it will be implemented
    Thanks anyway.
    Cheers,
    Harald
    Message was edited by: harlam2k11

  • How to write to log files using java files from JSP

    Anybody knows different options in writing to log files using JSP?

    Do you have an example?in the init() method of the servlet put the following
            FileOutputStream out = new FileOutputStream("your-log-file");
            PrintStream ps = new PrintStream(out);
            System.setOut(ps);
            System.setErr(ps);load the servlet on startup using <load-on-startup> in web.xml

  • Procedure for read/write an XML-File using UCCX9

    Hi Team!
    Is there someone who can explain me the procedure of reading/writing an XML-File using Cisco UCCX Rel. 9.0?
    In the last couple of days I did a lot of research on the partner community as well as reading the CRS-Editor-PDFs.
    But I can’t find a solution.
    There are some templates available but they all didn’t seem to work.
    I have two xml-files, both uploaded to “Document Management\en_us\”.
    The script itself is attached to this posting.
    I build that my script according to a sample script I found in the community.
    From my point of view I have configured my script exactly like the sample script.
    But it still doesn’t work.
    I am especially interested in where to store the the appropriate files.
    I would be very happy if there is someone who can explain me, what’s wrong there.
    Many thanks in advance.
    Kind regards
    Michael

    I'm experiencing the same issue [reading XML causes errors that say things from "no such file" to some odd Java exception.] I'm able to use a template XML file and after authenticating a user, transform the template into a proper XML file and then successfully save it to the en_US Doc Repository with updated values.
    However, no matter what I've tried or who I've asked, the READ on the XML file so that I can actually script something that does some routing based on the value of the XML file created in my first script? Ultra fail.
    I've even worked with three separate TAC IPCC engineers who were able to reproduce the issue in their test environment, but they were unable to assist. Eventually, whe pressed, I received this response from the last IPCC engineer.:
    "Hello Brad,
    Yes I know what I provided you with is what you already have achieved and this missing step is precisely what you need: how to setup the script to check the status and value of this XML document and then decide routing according to the state.   But unfortunately this is what I found internally.  The other resources are the ones you already know:  support forums, scripting guides.  The other resource with suggest to customer looking for script assistance is the Cisco Account Manager of your company, they know where to get the resources for such issues.   Then again as I mentioned before on our phone conversation TAC does not support scripting but certainly if I find something else on my side I will let you know for sure."
    I would do ponderous cartwheels of joy if someone who has this working in version 9.x [9.0.2 specifically] could share the deep magic.

  • How we write into properties file using get class method

    Hi
    I want to set some value into properties file using given code
    can any one please tell me how i can do this.
    property file
    setting.properties
    Name     =     abc
    and code I use is
    java.io.InputStream oInputStream = this.getClass().getResourceAsStream("Setting.properties");
                   Properties obj = new Properties();
                   obj.load(oInputStream);
                   String myName = obj.getProperty("Name");
                   System.out.println("myName :"+myName);
                   obj.setProperty("Name","def");
                   FileOutputStream oOutput= new FileOutputStream("Setting.properties");
                   obj.store(oOutput, "");
    thanks.

    You can't.
    If you have properties that change dynamically, you should not be using a properties file that sits in the classpath, you should be using Preferences, or a properties file that sits in some application or possibly even user directory, but not one in the classpath. The proper way to do this, would be to have a properties file in your jar (or otherwise in your classpath) that contains the defaults, and another one outside of the classpath in one of the twwo above mentioned areas, then, you read the default one only if the other doesn't exist, or you read the default one first, then read the other overwriting the values from the defaults.
    Don't forget to save the properties again (right after loading if you loaded, or always load, the defaults) after every change.

  • Is there some way for me to write to a file using JavaScript in LiveCycle

    Hi there,
    Our client has a requirement to be able to print off all validation messages from a partially completed e-form.  What I would like to do it create a text string and write it to a file so that the user can print it off.
    Is this possible to do using JavaScript in LiveCycle?
    Thanks,
    Kieran

    You'll have to get a Dremel motor tool and some fine metal bits, make a jig to hold the Dremel so it's stationary, then a slider jig for the MacBook Pro so the bit can drill into the center of the stuck plug.
    Gently push the MBP against the drill bit so it drills into the stuck plug.
    Once the hole is drilled down deep enough, use some metal to metal epoxy resin to glue the bit into the drilled hole, then let it set up according to directions.
    Take a pair of vise-grips and get a good grip on the bit portion sticking out and gently pull it straight out, if you bend or twist, you can snap off the bit.

  • Differenet BPEL instances write to same file using FileAdapter

    Hi,
    I want to write a file through BPEL using FileAdapter, But i dont want that whenever a new instance of BPEL is generated the new file is created.
    I want all instances to write to the same 1 single file. Is it possible?
    How can this be done?
    Looking forward for your answer.
    Thanks

    See : http://www.customware.net/repository/display/FUSION/File+Adapter+-+Appending                                                                                                                                                                               

Maybe you are looking for

  • How do you transfer voice memos to itunes?

    I am trying to transfer my voice memos to the latest version of iTunes but I cannot find a way. It used to be simple with the older versions, but now I am having trouble.

  • Problem with webutil_file_transfer.as_to_client

    Hi all, I am migrating some Forms/Reports from 6i to 10g, well, when i make a report sometimes i want to save some of those reports from server to client. For doing this i am using the WEBUTIL functinality with webutil_file_transfer.as_to_client. thi

  • Invoice Block --------- set tolearnce limit

    HI, Iam configuring Invoice block - set tolerance limits in logistics invoice verification. it listed some standard tolerance keys like AN, AP, BD,BV etc, is there any place where i can create one new custom tolearnce key.  my business requirement is

  • Finding out the permission(S)

    Hi, How to find out the set of permissions for a particullar user id on various table(S) that are present in the database, any objects for that matter??? and if i create a table a from my user id, will i have all the grants for that table by default.

  • I need to deactivate CS6

    I need to deactivate CS6 but I have already rebuilt my pc for the 2nd time