How can i write a string into a specified pos of a file?

How can i write a string into a specified pos of a file without read all file into ram and write the whole file again?
for example:
the content of file is:
name=123
state=456
i want to modify the value of name with 789
(write to file without read all file into ram)
How can i do it? thank you

take this as an idea. it actually does what i decribed above. you sure need to make some modifications so it works for your special need. If you use it and add any valuable code to it or find any bugs, please let me know.
import java.io.*;
import java.util.*;
* Copyright (c) 2002 Frank Fischer <[email protected]>
* All rights reserved. See the LICENSE for usage conditions
* ObjectProperties.java
* version 1.0, 2002-09-12
* author Frank Fischer <[email protected]>
public class ObjectProperties
     // the seperator between the param-name and the value in the prooperties file
     private static final String separator = "=";
     // the vector where we put the arrays in
     private Vector PropertiesSet;
     // the array where we put the param/value pairs in
     private String propvaluepair[][];
     // the name of the object the properties file is for
     public String ObjectPropertiesFileName;
     // the path to the object'a properties file
     public String ObjectPropertiesDir;
     // reference to the properties file
     public File PropertiesFile;
     // sign for linebreak - depends on platforms
     public static final String newline = System.getProperty("line.separator");
     public ObjectProperties(String ObjectPropertiesFileName, String ObjectPropertiesDir, ObjectPropertiesManager ObjectPropertiesManager)
     //     System.out.println("Properties Objekt wird erzeugt: "+ObjectPropertiesFileName);
          this.ObjectPropertiesFileName = ObjectPropertiesFileName;
          this.ObjectPropertiesDir = ObjectPropertiesDir;
          // reference to the properties file
          PropertiesFile = new File(ObjectPropertiesDir+ObjectPropertiesFileName);
          // vector to put the param/value pair-array in
          PropertiesSet = new Vector();
     //     System.out.println("Properties File Backup wird erzeugt: "+name);
          backup();
     //     System.out.println("Properties File wird eingelesen: "+PropertiesFile);
          try
               //opening stream to file for read operations
               FileInputStream FileInput = new FileInputStream(PropertiesFile);
               DataInputStream DataInput = new DataInputStream(FileInput);
               String line = "";
               //reading line after line of the properties file
               while ((line = DataInput.readLine()) != null)
                    //just making sure there are no whitespaces at the beginng or end of the line
                    line = cutSpaces(line);
                    if (line.length() > 0)
                         //$ indicates a param-name
                         if (line.startsWith("$"))
                              // array to store a param/value pair in
                              propvaluepair = new String[1][2];
                              //get the param-name
                              String parameter = line.substring(1, line.indexOf(separator)-1);
                              //just making sure there are no whitespaces at the beginng or end of the variable
                              parameter = cutSpaces(parameter);
                              //get the value
                              String value = line.substring(line.indexOf(separator)+1, line.length());
                              //just making sure there are no whitespaces at the beginng or end of the variable
                              value = cutSpaces(value);
                              //put the param-name and the value into an array
                              propvaluepair[0][0] = parameter;
                              propvaluepair[0][1] = value;
                         //     System.out.println("["+ObjectPropertiesFileName+"] key/value gefunden:"+parameter+";"+value);
                              //and finaly put the array into the vector
                              PropertiesSet.addElement(propvaluepair);
          // error handlig
          catch (IOException e)
               System.out.println("ERROR occured while reading property file for: "+ObjectPropertiesFileName);
               System.out.println("ERROR CODE: "+e);
               // System.out.println("in ObjectProperties");
     // function to be called to get the value of a specific paramater 'param'
     // if the specific paramater is not found '-1' is returned to indicate that case
     public String getParam(String param)
          // the return value indicating that the param we are searching for is not found
          String v = "-1";
          // looking up the whole Vector
          for (int i=0; i<PropertiesSet.size(); i++)
               //the String i want to read the values in again
               String s[][] = new String[1][2];
               // trying to get out the array from the vector again
               s = (String[][]) PropertiesSet.elementAt(i);
               // comparing the param-name we're looking for with the param-name in the array we took out the vector at position i
               if (s[0][0].equals(param) == true)
                    //if the param-names are the same, we look up the value and write it in the return variable
                    v = s[0][1];
                    // making sure the for loop ends
                    i = PropertiesSet.size();
          // giving the value back to the calling procedure
          return v;
     // function to be called to set the value of a specific paramater 'param'
     public void setParam(String param, String value)
          // looking up the whole Vector for the specific param if existing or not
          for (int i=0; i<PropertiesSet.size(); i++)
               //the String i want to read the values in again
               String s[][] = (String[][]) PropertiesSet.elementAt(i);
               // comparing the param-name we're looking for with the param-name in the array we took out the vector at position i
               if (s[0][0].equals(param) == true)
                    //if the param-names are the same, we remove the param/value pair so we can add the new pair later in
                    PropertiesSet.removeElementAt(i);
                    // making sure the for loop ends
                    i = PropertiesSet.size();
          // if we land here, there is no such param in the Vector, either there was none form the beginng
          // or there was one but we took it out.
          // create a string array to place the param/value pair in
          String n[][] = new String[1][2];
          // add the param/value par
          n[0][0] = param;
          n[0][1] = value;
          // add the string array to the vector
          PropertiesSet.addElement(n);
     // function to save all data in the Vector to the properties file
     // must be done because properties might be changing while runtime
     // and changes are just hold in memory while runntime
     public void store()
          backup();
          String outtofile = "# file created/modified on "+createDate("-")+" "+createTime("-")+newline+newline;
          try
               //opening stream to file for write operations
               FileOutputStream PropertiesFileOuput = new FileOutputStream(PropertiesFile);
               DataOutputStream PropertiesDataOutput = new DataOutputStream(PropertiesFileOuput);
               // looping over all param/value pairs in the vector
               for (int i=0; i<PropertiesSet.size(); i++)
                    //the String i want to read the values in
                    String s[][] = new String[1][2];
                    // trying to get out the array from the vector again
                    s = (String[][]) PropertiesSet.elementAt(i);
                    String param = "$"+s[0][0];
                    String value = s[0][1];
                    outtofile += param+" = "+value+newline;
               outtofile += newline+"#end of file"+newline;
               try
                    PropertiesDataOutput.writeBytes(outtofile);
               catch (IOException e)
                    System.out.println("ERROR while writing to Properties File: "+e);
          catch (IOException e)
               System.out.println("ERROR occured while writing to the property file for: "+ObjectPropertiesFileName);
               System.out.println("ERROR CODE: "+e);
     // sometimes before overwritting old value it's a good idea to backup old values
     public void backup()
          try
               // reference to the original properties file
               File OriginalFile = new File(ObjectPropertiesDir+ObjectPropertiesFileName);
               File BackupFile = new File(ObjectPropertiesDir+"/backup/"+ObjectPropertiesFileName+".backup");
               //opening stream to original file for read operations
               FileInputStream OriginalFileInput = new FileInputStream(OriginalFile);
               DataInputStream OriginalFileDataInput = new DataInputStream(OriginalFileInput);
               //opening stream to backup file for write operations
               FileOutputStream BackupFileOutput = new FileOutputStream(BackupFile);
               DataOutputStream BackupFileDataOutput = new DataOutputStream(BackupFileOutput);
          //     String content = "";
               String line = "";
               // do till end of file
               while ((line = OriginalFileDataInput.readLine()) != null)
                    BackupFileDataOutput.writeBytes(line+newline);
          // error handlig
          catch (IOException e)
               System.out.println("ERROR occured while back up for property file: "+ObjectPropertiesFileName);
               System.out.println("ERROR CODE: "+e);
               System.out.println("this is a serious error - the server must be stopped");
     private String cutSpaces(String s)
          while (s.startsWith(" "))
               s = s.substring(1, s.length());
          while (s.endsWith(" "))
               s = s.substring(0, s.length()-1);
          return s;
     public String createDate(String seperator)
          Date datum = new Date();
          String currentdatum = new String();
          int year, month, date;
          year = datum.getYear()+1900;
          month = datum.getMonth()+1;
          date = datum.getDate();
          currentdatum = ""+year+seperator;
          if (month < 10)
               currentdatum = currentdatum+"0"+month+seperator;
          else
               currentdatum = currentdatum+month+seperator;
          if (date < 10)
               currentdatum = currentdatum+"0"+date;
          else
               currentdatum = currentdatum+date;
          return currentdatum;
     public String createTime(String seperator)
          Date time = new Date();
          String currenttime = new String();
          int hours, minutes, seconds;
          hours = time.getHours();
          minutes = time.getMinutes();
          seconds = time.getSeconds();
          if (hours < 10)
               currenttime = currenttime+"0"+hours+seperator;
          else
               currenttime = currenttime+hours+seperator;
          if (minutes < 10)
               currenttime = currenttime+"0"+minutes+seperator;
          else
               currenttime = currenttime+minutes+seperator;
          if (seconds < 10)
               currenttime = currenttime+"0"+seconds;
          else
               currenttime = currenttime+seconds;
          return currenttime;

Similar Messages

  • How can I convert a String into an int?

    I need to use command-line args. So I enter "java Main 123" and I want to use 123 not as a String but as an int.
    How can I convert it into an int?
    Thank You!!
    Sprocket

    Example method (you don't need to use a method unless you do this a lot)
    private int stringTOInt (String aString)
    int result = 0;
    try
    result = Integer.parseString(aString);
    catch (Exception ex)
    System.out.println ("Failed to convert string " + aString + " to int.");
    return result;
    }

  • How can I convert a String into boolean?

    I am facing difficulty in converting String into boolean.
    For example, I have a few variable which i need user to input yes or no as the answer. But I uses string instead. Is there a way which i can ask them to input boolean directly?
    Please advise...
    credit = JOptionPane.showInputDialog("Enter Yes or No for Credit Satisfactory : ");
    System.out.println("The answer for Credit Satisfactory : "+credit);
    e_invtry=JOptionPane.showInputDialog("Enter Yes or No for inventry level");
    System.out.println("The answer for Quantity Order : "+e_invtry);
    Message was edited by:
    SummerCool

    Thanks...but I don't get it....I tried to use your
    suggestion but i got the message that " cannot find
    symbol method
    showConfirmDialog(java.lang.String,int)" ???
    Please advise.
    The code I use was :
    int credit = JOptionPane.showConfirmDialog("Enter Yes
    or No for credit satisfactory",
    JOptionPane.YES_NO_OPTION);Well that was not the example I gave you.
    JOptionPane has no method showConfirmDialog that receives a String and an int (exactly what the error message is telling you).
    What was wrong with the version I showed you?

  • How can I seperate one string into multiple strings using PowerShell?

    New to PowerShell...how can I read/separate parts of a file name? For instance if I have a file name like "part1_part2_part3_part4.xls", how to separate this file name to four different parts? So I basically want to go from that file name,
    to four different strings like part1, part2, part3, and part4...as four separate strings. How can I get this done in PowerShell?
    Thanks

    You can try something like this
    PS> (Get-ChildItem part1_part2_part3_part4.xls).BaseName.Split('_')

  • How can I write this string to a file as the ASCII representation in Hex format?

    I need to convert a number ( say 16000 ) to Hex string ( say 803E = 16,000) and send it using Visa Serial with the string control in Hex Mode. I have no problem with the conversion (see attached). My full command in the hex display must read AA00 2380 3E...
    I can easily get the string together when in Normal mode to read AA0023803E... but how can I get this to hex mode without converting? (i.e. 4141 3030 3233 3830 3345 3030 3030 3031 )
    Attachments:
    volt to HEX.vi ‏32 KB

    Sorry, The little endian option was probably introduced in 8.0 (?).
    In this special case it's simple, just reverse the string before concatenating with the rest.
    It should be in the string palette, probably under "additional string functions".
    (note that this only works in this special case flattening a single number as we do here. If the stat structure is more complex (array, cluster, etc.) you would need to do a bit more work.
    Actually, you might just use typecast as follows. Same difference.
    I only used the flatten operation because of the little endian option in my version.
    Message Edited by altenbach on 11-16-2007 11:53 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    littleendian71.png ‏4 KB
    littleEndiancast71.png ‏4 KB

  • How can I convert a string into an image

    I want to convert a string into an image.
    I want to know required steps for that.

    look at http://forum.java.sun.com/thread.jsp?forum=31&thread=194763
    drawString looks as something you might need

  • How can I import personal certificates into firefox that are not pkcs12 files (.cer or other)?

    I am trying to import .cer personal certificat into mozzila so I can go to an secure site (bank account online) but cannot do it since it is not pkcs12 type of file. Can you help me.

    I tied that, but when I try to import them to mozzila all it wants are pkcs12 files. It does not accept any other.

  • How can I send multiple string commands into a VISA write?

    Hi Fellow LabVIEW users
    I am very new to LabVIEW (2.5 months) so please forgive me if my lingo is not up to par.
    How can I send multiple string commands to a VISA write. For example each string command looks like this
    1) 3A00 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0033 (Scenario 1)
    2) 3A01 0000 0000 FFFF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0034 (Scenario 2)
    3) 3A01 0000 0000 33FF FFFF FFFF 0000 0000 FF00 0000 0000 0000 0000 0067 (Scenario 3).
    and so on and so forth. And there are a number of scenarios.
    Each String scenario will give a different string output which will be interpreted differently in the front panel.
    Right now I have to manually change the string commands on the front panel to give me the desired output. How can I do this without manually changing the commands i.e. hard coding each scenario into the block diagram?
    Thanks, any feedback will help.
    mhaque

    Please stick to your original post.

  • How to read and write a string into a txt.file

    Hi, I am now using BEA Workshop for Weblogic Platform version10. I am using J2EE is my programming language. The problem I encounter is as the above title; how to read and write a string into a txt.file with a specific root directory? Do you have any sample codes to reference?
    I hope someone can answer my question as soon as possible
    Thank you very much.

    Accessing the file system directly from a web app is a bad idea for several reasons. See http://weblogs.java.net/blog/simongbrown/archive/2003/10/file_access_in.html for a great discussion of the topic.
    On Weblogic there seems to be two ways to access files. First, use a File T3 connector from the console. Second, use java.net.URL with the file: protocol. The T3File object has been deprecated and suggests:
    Deprecated in WebLogic Server 6.1. Use java.net.URL.openConnection() instead.
    Edited by: m0smith on Mar 12, 2008 5:18 PM

  • How can I write into a table cell (row, column are given) in a databae?

    How can I write into a table cell (row, column are given) in a database using LabVIEW Database Toolkit? I am using Ms Access. Suppose I have three columns in a table, I write 1st row of 1st column, then 1st row of 3rd column. The problem I am having is after writing the 1st row 1st column, the reference goes to second row and if I write into 3rd column, it goes to 2nd row 3rd column. Any suggestion? 
    Solved!
    Go to Solution.

    When you do a SQL INSERT command, you create a new row. If you want to change an existing row, you have to use the UPDATE command (i.e. UPDATE tablename SET column = value WHERE some_column=some_value). The some_column could be the unique ID of each row, a date/time, etc.
    I have no idea what function to use in the toolkit to execute a SQL command since I don't use the toolkit. I also don't understand why you just don't do a single INSERT. It would be much faster.

  • How can I write bits through the COM1 serial port?

    I'm trying to write bits through the serial port COM1.
    Labview "Write VI" only writes everything in string. It seems. How can I write bit by bit through COM1?
    Thank you,
    Van

    Serial transmission (COM port) protocol requires sending a group of bits at one time. You cannot just send one bit. Standard COM port settings must be either 7 or 8 data bits, 1 or 2 stop bits, etc... You have to group your bits 7 or 8 at a time. You could probably send a 0 byte or a 1 byte. This would be like sending 0000 0000 for a low bit and 0000 0001 for a high bit. Your receiving end would have to know how to interpret what you are sending if you choose this method. Of course you have to convert your byte into a string before sending to COM port. Wire a U8 data type to a Build Array input. Then wire the array output to a Byte Array to String input. The output of this function will be the character representation of your byte suitable for sending acr
    oss a serial port.
    - tbob
    Inventor of the WORM Global

  • How can I convert page points into document points??

    Hello,
    How can I convert page points into document points? any API?
    I have found 2 APIs
    AIDocumentViewSuite::ArtworkPointToViewPoint( ) and
    AIDocumentViewSuite::ViewPointToArtworkPoint( )
    but I dont know what is view point and art work point.
    I think artwork point = page points and view points = document points. am I correct ???

    What do you mean by 'document points'? Do you mean document units? Like centimeters or inches? If that, there's no API to do (well, kind of in AIUser.h, but that gives you back a string with a unit suffix). Frankly, its pretty easy to just figure out the conversion values for each type of ruler unit -- there are only five or so you need -- and then write a dinky function that takes a value in one or the other, looks up the current document unit and uses that to convert the value (one function for each way). You just need to figure out everything in terms of points (since pixels == points) -- in that regard, it probably helps to know that 72 pt == 1 inch. From that you can figure out pointer-per-inch|centimeter|millimeter|pica.

  • HOW DO I WRITE A STRING TO FLAG WHEN A CELL HAS OR 17 CHARACTERS?

    HOW DO I WRITE A STRING TO FLAG WHEN A CELL HAS < OR > 17 CHARACTERS?

    Hi Tassytiger,
    A "string" is just a string of characters. Examples are qwerty, 123abc, 43πbono. there are several ways to write one. A more precise description of your end goal might help answer "How do I write a string."
    To the current version of your specific question:
    What I actually need to achieve is a situation where, when I enter <17 Char. or >17 Char.
    inadvertently then tab to the next cell, I get the following response in the active cell:
    The cell immediately below "17 character ID" displays an error triangle. These are shown when the formula in a cell produces an error message. they are system generated and require two things to happen: The cell must contain a formula AND something must have happened to cause that formula to produce an error.
    I don't wish to add any columns to my s/s but would like to apply the rule to the current column just as i would change the text or fill colour.
    The difficulty there is that a cell may contain entered data, OR it may contain a formula. You want to enter data (a string of characters) and you want to produce an error triangle if that string has more or fewer than 17 characters. Evaluating the length of the string requires a formula. Getting the string into the cell requires direct entry (in your scenario). The two are not compatible within the content of a single cell.
    Terry's example uses a formula in column B to measure the length of the string in column A. If the length is 17 characters, the IF statement produces the empty string ( "" ), and the cell in column B appears empty. If the string is not 17 characters long, the IF statement produces the string "Not 17 Chars!"
    His formula is easily changed to produce an error triangle in place of "Not 17 Chars!":
    B1: =IF(LEN(A1)=17, "",17/0)
    In this version, if the length of the string in A1 is not 17 (characters), the formula will attempt to divide 17 by 0, and will produce a 'division by zero' error.
    But, as with all of the other suggestions, this one will require a new column to provide space for the formula and it's result.
    Changing the text or fill colour can be done using conditional formatting. Changing content of the cell (eg. choosing between the entered string of characters and the error triangle) cannot.
    Conditional formatting rules compare the content of a the cell to be formatted with either a fixed value (written into the rule) or to the content of another cell. In my examples (and in Ian's examples) above the rules compared the content of the cell to be formattes to the number '17'. The number was generated by a formula which measured the length (in characters) of the text in the cell where the ID was entered, and reported that length as a number.
    A way to show a red triangle using conditional formatting is to use Image fill as the default fill of the cell, then use a colour fill as the conditional fill to hide the trialngle when the conditions are met. Here's the same example as used above, with this technique applied to column B:
    The same formula is used in column B as in my previous example. Type size is set to 1 point (note the black dot, visible in the green filled cell) to keep the numbers from obscuring the triangles. The triangles are shapes, inserted onto the canvas (not into the table) from the Shapes button in the tools. Their fill colour has been changed to red, a 12 point exclamation sign character ha been typed into the shape and its text colour set to white, and the triangle's size has been reduced as much as possible without triggering the overflow symbol (boxed plus sigh) to appear.
    The triangle image (and some of its white background) was made into a png image file by taking a screen shot, and the image was inserted into all of the cells in the body rows of column B as an image fill, using the Graphic inspector. The conditional format rule below was then applied to the body row cells in column B.
    Finally, you can apply conditional formatting to the cell containing the ID. This will still require another column to contain the values to which the content of the ID cell will be compared, but that column may be hidden, or may be located on a separate table.
    The method requires an second cell for each cell contining an ID, and uses a formula that makes the contents of the second cell the same as that of the ID cell IF the ID cell contents are 17 characters long.
    Here's a sample. Table 1 is column A of the same table as above. Table 2 is a single column table holding the comparison cells.
    As in the example above, the cells on table 1 were given an image fill. The conditional format rule replaces that with a white colour fill when the cell contains the same text as its partner cell in Table 2.
    This is the rule for cell A2. In A3, the cell reference is to Table 2::A3, and in A4, to Table 2::A4. The cell references in conditional format rules must be edited individually.
    Regards,
    Barry

  • How can i write info in text filefrom servlet

    hello
    can u give me exmaple how can i write data into text file from servlet ?
    Edited by: bla123456789654 on May 17, 2010 2:05 PM

    javax.servlet.GenericServlet
    public void log(java.lang.String msg)
    Writes the specified message to a servlet log file, prepended by the servlet's name.
    See ServletContext.log(String).
    Parameters:
            msg - a String specifying the message to be written to the log file
    */

  • How can I write a program that compiles without warnings?

    I tried the following with the 1.5 beta-compiler (build 28; I think):
    class Y {
         public static final class Pair<X,Y> {
           private X fst;
           private Y snd;
           public Pair(X fst, Y snd) {this.fst=fst; this.snd=snd;}
           public X getFirst() { return fst; }
           public Y getSecond() { return snd; }
           public String toString() { return "("+fst+","+snd+")"; }
      public static void main(String... args) {
         Pair[] pairArr = new Pair[10];              // supposed to be an array of Pair<Integer,Integer>
         for (int i=0; i<pairArr.length; i++)
             pairArr[i] = new Pair<Integer,Integer>(i,i);
         for (int i=0; i<pairArr.length; i++) {
             Pair<Integer,Integer> p = pairArr; // unchecked warning
         System.out.println(p);
         Integer first = p.getFirst();
         Integer second = p.getSecond();
    // ... more stuff ...
    It turns out that I get an unchecked warning when I extract an element from the array of pairs. Okay, that's fine. How can I avoid the warning? I had expected that an explicit cast would help.
      Pair<Integer,Integer> p = (Pair<Integer,Integer> )pairArr;
    With a cast I'm telling the compiler: "I _know_ what I'm doing; please trust me." But the compiler still issues a warning.
    How can I write a warning-free program in this case? The only thing I can think of, is not using the parameterized type Pair in its parameterized form. But it's not the idea of Java Generics that I refrain from using parameterized types. What am I missing?

    It turns out that I get an unchecked warning when I
    extract an element from the array of pairs. Okay,
    that's fine. How can I avoid the warning? I had
    expected that an explicit cast would help.
    Pair<Integer,Integer> p = (Pair<Integer,Integer>
    )pairArr;
    With a cast I'm telling the compiler: "I _know_ what
    I'm doing; please trust me."  But the compiler still
    issues a warning.  Yes, but at least you were able to change the warning from "unchecked assignment" to "unchecked cast" which is a little shorter ;-)
    Seriously , since arrays of generic types are disallowed, there is probably no way to get rid of these warnings - which makes a strong point for eliminating "unchecked" warnings altogether (see the other thread "selectively suppressing compiler warnings")
    Cheerio,
    Gernot

Maybe you are looking for

  • Error when creating a new project in sharepoint

    I am getting this error "Failed to create site. A duplicate field name "workflow_history" was found" when I am creating a new project on share point. Can someone help me identify and fix this issue exactly.

  • My Nano will no longer sync with iTunes. Sync is greyed out under Devices.

    My Nano will no longer sync with iTunes. Sync is greyed out under Devices.

  • Cannot toggle "Access on Lock Screen" in Control Center Settings

    I noticed the other day that the Control Center was disabled from accessing it from the lock screen.  I went into Settings-->Control Center to turn it back on and I discovered that the "Access on Lock Screen" option is grayed-out or locked such that

  • $PATH environment variable setting

    This question is for the Terminal.app UNIX wizards out there. I'm wondering where the default $PATH variable setting is established by the operating system. I know I can modify this variable's setting in my .bash_profile or .profile files, but that i

  • HKLM Permissions lost after reboot

    Hello All. I have a need to give the Everyone group full control over the root HKLM hive of the registry. I have used the RegEdit GUI and the regini command to grant full control to the Everyone group for the HKLM Key and Subkeys. However, once I reb