Inserting strings in a RandomAccessFile at a particular location

I wrote a java program to read and display the contents of RAF. It is working. Actually,I need to read a file and search for a string in it and if the string equals certain value, then i need to insert a line in the file at that location.
My problem is I am not able to insert any string in the RandomAccessFile(RAF) at a particular location, it always overwrites the already present string.
I have a file called SOE_Arrays2.js which needs to be read and its content has to be modified. I am searching for a string like "os = [" in it and inserting another line like "["64w","64-bit Windows"]," at that location.
the file looks like this:
os1 = [
["win","Windows"],
["unx","UNIX"],
["mvs","MVS"]
os2 = [
["alp","Alpha VMS"],
["lnx","Linux"]
var letter = [
["new","New"],
["addon","Add-on"],
["lsf","LSF"],
["renew","Renewal"]
The java program i wrote is here:
import java.io.*;
public class RAFtest
     public void writeTo()
          try
     String f = "C:\\webapps\\oncall\\soe\\SOE_Arrays2.js";
     File arrayfile = new File(f);
     RandomAccessFile raf = new RandomAccessFile(arrayfile, "rw");
     String s="",ss="";
     int i,j = 0,len;
     long fp;
while((s = raf.readLine()) != null)
          //System.out.println(s);
          int ptr = 0;
          ptr = s.indexOf("os2 = [");
          if(ptr != -1)
               System.out.println(s);
               System.out.println("The OS array is here:");
               ss = s;
               raf.writeBytes("\r\t");
               fp = raf.getFilePointer();
               raf.seek(fp-4);
          raf.writeBytes("[\"64w\",\"64-bit Windows\"],\r");
               break;
     raf.close();     
     catch(Exception e){e.printStackTrace(System.out);}      
     public static void main(String args[])
          RAFtest e = new RAFtest();
          e.writeTo();
After executing the code SOE_Arrays2.js looks like this:
os1 = [
["win","Windows"],
["unx","UNIX"],
["mvs","MVS"]
os2 = [["64w","64-bit Windows"],
lnx","Linux"]
var letter = [
["new","New"],
["addon","Add-on"],
["lsf","LSF"],
["renew","Renewal"]
you can see that RAF overwrites to the file at that particular location( after the line "os2 = [ ". What i need is to insert the text at a particular location, Is there a way to do this?
I tried to insert carriage return, etc and move the file ptr back a little and write, whatever it is, RAF overwrites it, is there a way to insert instead of overwrite?
Basically I want to get some string from the user from a web page and insert that string in my SOE_Arrays2.js file at a particular location depending on certain conditions.
Is there another way of doing this instead of RAF?
Please let me know how to do this.
Thanks,
Priyha.

Hi DrClap,
Thanks for the clarification. Everything works except the renameTo() . I am trying to rename the arrayfile2 to arrayfile1 , but the rename always return false. I am not sure why rename is not successful.
I checked for the permissions of the file, full permission is there. I closed the files before renaming.
Here's the code.
import java.io.*;
public class RAFtest
public void writeTo()
try
String f1 = "C:\\JAVA\\SOE_Arrays2.js";
String f2 = "C:\\JAVA\\SOE_Arrays3.js";
File arrayfile1 = new File(f1);
File arrayfile2 = new File(f2);
RandomAccessFile raf1 = new RandomAccessFile(arrayfile1, "rw");
RandomAccessFile raf2 = new RandomAccessFile(arrayfile2, "rw");
long fp1=0,fp2=0; // file pointers
String s="",ss="";
int i,j = 0,len;
boolean b= false;
raf2.seek(0);
while((s = raf1.readLine()) != null)
int ptr = 0;
raf2.writeBytes(s);
ptr = s.indexOf("var OS9.1_sol = [");
     if(ptr != -1)
          System.out.println(s);
          System.out.println("The OS array is here:");
          ss = s;
          fp1 = raf1.getFilePointer();
          raf2.writeBytes("[\"64w\",\"64-bit Windows\"],");
          fp2 = raf2.getFilePointer();
          break;
raf1.seek(fp1);
while((s = raf1.readLine()) != null)
     raf2.writeBytes(s);               
raf1.close();
raf2.close();
if(arrayfile2.exists()) System.out.println("file2 exists!");
try{
b = arrayfile2.renameTo(arrayfile1); //rename the file, why does it return false?
}catch(SecurityException se){se.printStackTrace(System.out);}
catch(NullPointerException ne){ne.printStackTrace(System.out);}
System.out.println("b: "+b);
catch(Exception e){e.printStackTrace(System.out);}
public static void main(String args[])
RAFtest e = new RAFtest();
e.writeTo();
here is the SOE_Arrays2.js
var OS9.1 = [
["win","Windows"],
["unx","UNIX"],
["mvs","MVS"]
var OS9.1_sol = [
["alp","Alpha VMS"],
["lnx","Linux"]
var letter = [
["new","New"],
["addon","Add-on"],
["lsf","LSF"],
["renew","Renewal"]
Please let me know whats wrong with the above code. I have no clue why renameTo returns false.
Thanks,
Priyha

Similar Messages

  • Inserting strings in a database

    Hello all!
    I am trying to insert string values in a database with this metode.
        public void insertData(){
       try{
    String url = "jdbc:odbc":"+database;
    Connection connection = DriverManager.getConnection(url, user, password);
    Statement status = connection.createStatement();
    status.executeUpdate("INSERT INTO radiograhy (Title, Red, Green, Blue,"
    + "Hue,Saturation,Value,Color,Path,IdRadiography,Description) VALUES "
    +"("+Title+","+Red+","+ Green+","+ Blue +","
    + Hue+","+Saturation+","+Value+","+Color+","+Path+","
    +IdRadiography+","+Description+")");
    }catch(SQLException e){
    e.printStackTrace();
    System.out.println(e);
    but the metode throws me an exception :
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

    This has actually nothing to do with JDBC, but with basic SQL knowledge.
    Print the complete query using System.out.println and try to find out what's wrong with it. Play with it, execute it right on the DB, etcetera. If you don't understand it, then don't bother to read some SQL tutorials how to write clean SQL.
    Once you understand SQL, I would also recommend you to use PreparedStatement instead.

  • Inserting strings over 2000 in length

    Hi,
    I'm trying to populate a database table which contains a long and
    I've been running into two Oracle errors:
    ORA-01462: cannot insert string literals longer than 2000
    characters
    and
    ORA-01489: result of string concatenation is too long
    Can someone point me to documentation or a solution of how you
    can get a 29k string into the database? I have code regarding how
    to use LOBs, but I'm unfamiliar with any stored procedures which
    will allow you to append to a long column with new content. I
    need to use long for the project I am working on.
    Thanks in advance for your help!
    Jill
    null

    Hi Ralf,
    If you read the documentation on
    http://java.sun.com/products/jdbc/index.html you will
    find a statement saying that the JdbcOdbcDriver is
    only for test and experimental use.Yes, but my and other's experiences with the JDBC-ODBC bridge itself are very well.
    Since it is only a bridge over the specific vendor's ODBC driver, you are limited to the capabilities of that.
    But the bridge is not to blame for this.
    For MS products you may reach efforts by updating to an actual MDAC version.
    Nethertheless, with MS ODBC there are some problems.
    Search the driver database (a link is on the above web
    page) for another (commercial) driver. I recommend the
    type 4 driver from i-net.Ok.
    Have you tried out that error David reported with the i-net driver?
    I use JDBC-ODBC with MS SQLServer 2000, actual MDAC, and I get that error with PreparedStatement.
    But it's all ok with a normal statement.
    So if you could test them both with the i-net driver, we would see if it's again the MS ODBC driver.
    Regards,
    Ralf SchumacherI think, I'm not the first you asks this:
    you are not the quick one we saw in Suzuka on Sunday, are you?

  • Inserting String data to BLOB column

    Hi All
    I want to insert String data into BLOB column using DBAdapter - through database procedure.
    anybody can help?
    Regards
    Albin Issac

    I have used utl_raw.cast_to_raw('this is only a test')).But for bigger string I get the error as "string literal too long" do we have any similar function for longer string.
    Thanks,
    -R

  • Problem in Inserting string in mysql databse

    Hi all,
    I am trying to insert string in mysql using java query.As I have taken field varchar,that should be in single quotes,whereas string is having double quotes...so as I am trying to insert data that gives null value all the time.
    I did like:
    String name=jTextFieldname.getText();
    String sql="insert into record_master values (name,orderno,email,dob,address,mobile)";Any pointers are appreciable.
    Regards,
    Palak

    Oh I got the sollution...Tat was something like:
    String sql = "INSERT INTO record_master (name, orderno,email,dob,address,mobile,imeino) " +
    "VALUES('" + name + "', '" + orderno + "','" + email + "','" + dob +"','" + address +"','" + mobile + "','" + imei + "')";
    Regards,
    Palak

  • When i insert string text in hebrew i see ?????????

    hi
    when i insert string text in hebrew i see ????????? how to fix it ?
    i work on:
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
    Oracle Developer ver. 2.1.1.64
    thanks

    i try this, but still same problem :(
    my Settings:
    NLS_LANGUAGE     AMERICAN
    NLS_TERRITORY     AMERICA
    NLS_CURRENCY     $
    NLS_ISO_CURRENCY     AMERICA
    NLS_NUMERIC_CHARACTERS     .,
    NLS_CHARACTERSET     IW8MSWIN1255
    NLS_CALENDAR     GREGORIAN
    NLS_DATE_FORMAT     DD-MON-RR
    NLS_DATE_LANGUAGE     AMERICAN
    NLS_SORT     BINARY
    NLS_TIME_FORMAT     HH.MI.SSXFF AM
    NLS_TIMESTAMP_FORMAT     DD-MON-RR HH.MI.SSXFF AM
    NLS_TIME_TZ_FORMAT     HH.MI.SSXFF AM TZR
    NLS_TIMESTAMP_TZ_FORMAT     DD-MON-RR HH.MI.SSXFF AM TZR
    NLS_DUAL_CURRENCY     $
    NLS_COMP     BINARY
    NLS_LENGTH_SEMANTICS     BYTE
    NLS_NCHAR_CONV_EXCP     FALSE
    NLS_NCHAR_CHARACTERSET     AL16UTF16
    NLS_RDBMS_VERSION     11.2.0.1.0

  • Insert string containing '&'

    How to insert string containing '&' into a table
    INSERT INTO TBL_CHANGES_ORGANISATIES(CHANGE_MANAGEMENT_ID, SUBMITTER) VALUES ('HM0000002147848|TK0000003121328','CS CSU S\&B Change Management')

    if you're in sqlplus:
    put set define offprior to running your insert.
    if you're in Toad, either:
    put set define offbefore your insert statement, and run both in as a script
    OR
    right mouseclick on the editor and untick the "Prompt for substitution variables", and you need never worry about the & again!

  • Help with placing the JComponents at a particular location in JPanel

    Hello All,
    I think it is simple in placing JLabel with an icon or just just text at a particular location in the JPanel. But it is notworking. I know it is very simple but i think i am missing something. Here is code please help with this code.
    Thanks
    Smithaimport java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.LayoutManager;
    import javax.swing.*;
    public class DocumentGraphicalRepresentation {
         public void buildDocumentation() {
              JFrame frame = new JFrame("Graphical Representation");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setBounds(0, 0, 475, 265);
              JPanel panel = new JPanel();          
              panel.setBounds(0, 0, 475, 265);
              panel.setBackground(Color.lightGray);
              //panel.setLayout(new BorderLayout());          
              JLabel label0 = new JLabel(new ImageIcon("c:/arrow.gif"));
              label0.setLocation(61, 68);
              label0.setOpaque(false);
              panel.add(label0);
              JLabel label1 = new JLabel(new ImageIcon("c:/bulb.gif"));
              label1.setLocation(338, 139);
              label1.setOpaque(false);
              panel.add(label1);
              frame.getContentPane().add(panel);
              frame.setVisible(true);          
         public static void main(String args[]) {
              DocumentGraphicalRepresentation document = new DocumentGraphicalRepresentation();
              document.buildDocumentation();
    }

    When adding components to a null layout you must set both a location and size for them to show up.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.LayoutManager;
    import javax.swing.*;
    public class DGR {
         public void buildDocumentation() {
              JFrame frame = new JFrame("Graphical Representation");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setBounds(0, 0, 475, 265);
              JPanel panel = new JPanel();          
              panel.setBounds(0, 0, 475, 265);
              panel.setBackground(Color.lightGray);
              //panel.setLayout(new BorderLayout());          
              JLabel label0 = new JLabel(new ImageIcon(//"c:/arrow.gif"));
                                         "images/geek/geek-----.gif"));
                    Dimension d = label0.getPreferredSize();
                    label0.setSize(d);
              label0.setLocation(61, 68);
    //          label0.setOpaque(false);
              panel.add(label0);
              JLabel label1 = new JLabel(new ImageIcon(//"c:/bulb.gif"));
                                         "images/hawk.jpg"));
                    d = label1.getPreferredSize();
                    label1.setBounds(338,139,d.width,d.height);
    //          label1.setLocation(338, 139);
              System.out.println("label1.isOpaque = " + label1.isOpaque());
    //          label1.setOpaque(false);
              panel.add(label1);
              frame.getContentPane().add(new JScrollPane(panel));
              frame.setVisible(true);          
         public static void main(String args[]) {
              new DGR().buildDocumentation();
    }

  • Add node at particular location in XML file

    I'd like to add an item to a particular location in an XML file.  Location of parent node is given by string variable "itemtoaddto" and the XML file is given by "myXML":
    function TraverseXMLfile(itemtoaddto,myXML): void {
        var AttributeList:XMLList = myXML.attributes() + myXML.*.attributes() + myXML.*.*.attributes();
         for each (var labelname:XML in AttributeList) {
          if(labelname == itemtoaddto){
            trace (labelname + "match found!!!!!");
            myXML.*.labelname.appendChild(<SON name="Will" bday="01/15" />);
    In the above code, the parent item is being found in fact it's printing the "match found!!!!!" message.  However, the line
           myXML.*.labelname.appendChild(<SON name="Will" bday="01/15" />);
    is giving the following error:
         TypeError: Error #1086: The appendChild method only works on lists containing one item.
    Can someone help please? thanks.

    var myXML:XML = <product>
                                <subAssembly label="Sub1">&#8232;           
                                    <part label="Part1_1"/>&#8232;           
                                    <part label="Part1_2"/>&#8232;           
                                    <part label="Part1_3"/>&#8232;           
                                    <part label="Part1_4"/>&#8232;       
                                </subAssembly>&#8232;       
                                <subAssembly label="Sub2">&#8232;           
                                    <part label="Part2_1">&#8232;               
                                        <feature label="Feature2_1_1"/>&#8232;               
                                        <feature label="Feature2_1_2"/>&#8232;           
                                    </part>&#8232;           
                                    <part label="Part2_2">&#8232;               
                                        <feature label="Feature2_2_1"/>&#8232;               
                                        <feature label="Feature2_2_2"/>&#8232;           
                                    </part>&#8232;       
                                </subAssembly>&#8232;       
                                <subAssembly label="Sub3"> &#8232;           
                                    <part label="Part3_1">&#8232;               
                                        <feature label="Feature3_1_1"/>&#8232;               
                                        <feature label="Feature3_1_2"/>&#8232;           
                                    </part>&#8232;       
                                </subAssembly>&#8232;
                            </product>;
    myXML.subAssembly.(@label == "Sub1")[0].insertChildAfter(myXML.subAssembly.(@label == "Sub1")[0].part[myXML.subAssembly.(@label == "Sub1").part.length() - 1], <part label="Part1_5"/>);
    trace(myXML);
    This traces:
    <product>       
      <subAssembly label="Sub1">          
        <part label="Part1_1"/>      
        <part label="Part1_2"/>
        <part label="Part1_3"/> 
        <part label="Part1_4"/>
        <part label="Part1_5"/>
      </subAssembly>
      <subAssembly label="Sub2">
        <part label="Part2_1">        
          <feature label="Feature2_1_1"/>      
          <feature label="Feature2_1_2"/>    
        </part>  
        <part label="Part2_2">      
          <feature label="Feature2_2_1"/>      
          <feature label="Feature2_2_2"/>   
        </part>
      </subAssembly>
      <subAssembly label="Sub3">
        <part label="Part3_1">       
          <feature label="Feature3_1_1"/>     
          <feature label="Feature3_1_2"/>
        </part>
      </subAssembly>
    </product>

  • Uploading a file, renaming it and placing it in a particular location on server

    A user submits a file from a front end HTML form which has fields like Division, Department name, department number,
    section number, year, email, phone etc. The file being submitted might have a user given name. But, when it is 
    uploaded I want it to be named as Departmentname_departmentnumber_sectionnumber. So, if department is Accounting, 
    dept number is 123 and section is 1, name of file will be Accounting_123_1.doc The extension will be whatever type 
    of file(text, MS-Word's .doc or .docx, PDF or RTF) was submitted and the user can upload attachments of files with 
    extension .txt, .doc, .docx, pdf, rtf only.
    Also, I want it to be stored on a particular location on server. So, if Division is Corporate Finance and year is 
    2011-2012 it should be stored on server at "E:\Files Submitted\2011-2012\Corporate Finance\". The "E:\Files
    Submitted\" part remains same in the directory name.
    <cfset submittedfileName =
    #form.departmentname#&"_"&#form.departmentnumber#&"_"&#form.section_number_1#&"."&#cffile. ClientFileExt#>
    <cfset filedirectoryYear = "E:\Files Submitted\"&#form.current_year#&"\"&#form.division#&"\">
    <!--- ensure that the user uploads attachments of type with extension .txt, .doc, .docx, pdf, rtf only--->
    <cfif FORM.attachment_1 neq "">
           <cffile action="upload"
                   accept="text/plain,application/msword,application/pdf,application/rtf"          
                     filefield="attachment_1"
                     destination="E:\temp\uploads"
                     nameconflict="Makeunique"
            >
    <!--- rename the file and move it to permanent destination --->        
            <cffile
      action="rename"
      source="E:\temp\uploads\#cffile.serverFileName#"
      destination=#filedirectoryYear#&#submittedfileName#&#cffile.ClientFileExt#
      >
    <!---   now create a temporary variable for the attachment so that it can be emailed later on --->
    <cfset attachment_local_file_1 = #filedirectoryYear#&#submittedfileName#&#cffile.ClientFileExt#>
    </cfif>
    I used the cffile.ClientFileExt because the files were getting uploaded without the extension but am receiving an
    error at   destination=#filedirectoryYear#&#submittedfileName#&#cffile.ClientFileExt# as "multiple items at this
    position: Missing Token > or /> .
    I am using Coldfusion 8. Any suggestions would be appreciated on where I am erring and how I can fix it.

    Thanks Dan,
    The space between 'l' and 'e' was a formatting error while I was pasting text to this forum.
    Currently, I have
    <cfset filedirectoryYear = "E:\Files Submitted\"&#form.current_year#&"\"&#form.division#&"\">
    <cfif FORM.attachment_1 neq "">
           <cffile action="upload"
                   accept="text/plain,application/msword,application/pdf,application/rtf "          
                     filefield="attachment_1"
                     destination="E:\temp\uploads"
                     nameconflict="Makeunique"
            >
    <!--- rename the file and move it to permanent destination --->        
    <cfset submittedfileName =
    #form.departmentname#&"_"&#form.departmentnumber#&"_"&#form.section_number_1#&"."&#cffile. ClientFileExt#>
    <cfset presentfileName = #cffile.serverFileName#&"."&#cffile.ClientFileExt#>
            <cffile
      action="rename"
      source="E:\temp\uploads\#presentfileName#"
      destination=#filedirectoryYear##submittedfileName#
      >
    <!---   now create a temporary variable for the attachment so that it can be emailed later on --->
    <cfset attachment_local_file_1 = #filedirectoryYear#&#submittedfileName#&#cffile.ClientFileExt#>
    </cfif>
    <cfset attachment_local_file_1 = #filedirectoryYear#&#submittedfileName#>
    When I submit, I get the error message
    "Attribute validation error for tag CFFILE.
    The value of the attribute source, which is currently c:\Course Syllabi\uploads\Web Based System Two Page HandOut.pdf, is invalid and the line below is referred.
    destination="#filedirectoryYear##submittedfileName#"
    The filedirectoryYear path exists i.e. I have E:\Files Submitted\2011-2012\Finance. What could be the issue?
    P.S. I got it working, The filedirectoryYear path value was not the actual directory path\name in the filesystem. Once I had the
    correct name in the filesystem, the application worked fine.

  • Saving the file to a particular location!!!

    Hi,
          I have to upload a file and the file uploaded should be saved to aparticular location. For Example if i upload a file named 'eg.jpeg.' , how can i save this file to a particular location in the system?
    Regards,
    Shiny

    Hi,
    If you just want to display it within the same BSP application, try this:
    <htmlb:image src="eg.jpg" />
    If you want to retrieve the image from a non BSP application, I think you should look at logical files and paths (transaction AL11).
    Regards,
    Tanguy

  • Uploading File to a particular location

    Hi,
    I need to upload a file to a particular location using the Struts framework.
    I have been reading about the html:file tag.
    But I did not come across any information as to where the file gets uploaded to. I need the file to be uploaded to a location in my project.
    How do I do it?
    Could anyone post a code sample for this?
    Thanks in advance.

    http://www.google.com/search?q=struts+file+upload
    I see lots of useful examples tho.
    Saving the retrieved file to a particular location has nothing to do with Struts. Just handle it in your Javabean. Check the java.io API.

  • How do you place a video clip at a particular location in imovie

    how do I place a video clip at a particular location in imovie?

    You'll probably have better luck with an iMovie question if you ask in the iMovie forum.
    Regards

  • Automate saving a generated PDF at a particular location ?

    Hi,
    I am generating a PDF out of a simple form. I have to save this generated PDF at a particular location  (intranet). Can anybody give me the steps?
    Thanks
    Srinivas

    Hi,
    If you want to upload the pdf files from desktop to the server, then you can upload them in portal KM repository.
    Regards
    Srini

  • Saving PDF From in particular location

    Hi all,
    I am having one query i have a requirement that the form that is initiated should be stored in particular location.
    eg: i have initiated the form with input ABC in one filed and my requirement is that after final approval the file should create a folder ABC and PDF should stored  in that folder like abc.pdf
    C:\\ABC\ABC.pdf
    please let me know how can i do in the work flow.
    thanks in advance
    Sekhar

    The following operation will do that.
    Service Name: File Utilities
    Operation Name: Write Document
    Note: The file cannot be written on the client PC.
    Nith

Maybe you are looking for