Replace specific string in a file while reading it

Hi,
I am kind of an in between learner & intermediate programmer. I am trying to replace a specific string pattern in a file by reading it using BufferedReader & BufferedWriter. I tried it for 2 days. Can anyone give me a piece of code which reads a file line by line and replaces the specific string format with other? I tried replaceAll(regex,replacement). Nothing is working.

Hi Torajirou,
Thanks for the code. But, looks like
. But, looks like it is giving me a static method
problem. It says a static method should beaccessed
in a static way(f1.replace in main). Here is the
code. Can you help me with this?
import java.io.*;
public class FileReadWrite1{
public static void replace(File file, Stringregex,
String replacement) throws
FileNotFoundException,IOException {
     if (file == null) {
throw new IllegalArgumentException("File should
uld not be null.");
     if (!file.exists()) {
throw new FileNotFoundException ("File does not
not exist: " + file);
     if (!file.isFile()) {
throw new IllegalArgumentException("Should not be
be a directory: " + file);
     if (!file.canWrite()) {
throw new IllegalArgumentException("File cannot be
be written: " + file);
File tempFile = File.createTempFile("temp",
mp", "temp");
BufferedReader reader = new BufferedReader(new
(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new
(new FileWriter(tempFile));
try{
while (true) {
String line = reader.readLine();
if (line == null) {
break;
line = line.replaceAll(regex,replacement);
writer.write(line);
writer.newLine();
writer.close();
reader.close();
file.delete();
tempFile.renameTo(file);
}catch (Exception e) {
     System.out.println("Exception occured :"+e);
public static void main(String[] args) {
     FileReadWrite1 f1 = new FileReadWrite1();
     File file = new File("C:\\Temp\\src1.txt");
     String regex = "us.mi.state";
     String replacement = "us.tx.state";
     f1.replace(file,regex,replacement);
}when I wrote it, I was sober and bored
now I'm drunk and amused
god
did you try and remove the magic "static" keyword ?
I wrote it static because I didn't refer to any class
member when I wrote it and that's what I felt
compelled to do, though I feel nowadays writing
anyting static suggests some design mistake
somewhere
blahblahblahblahblahs/blahblahblahblahblah/blahblahblahblahblahblah
(forgot a "blah")

Similar Messages

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • Windows Cannot Access Specific Device, Path or File While Using Adobe Reader XI, Version 11.0.06

    Hello,
    Recently, I have been experiencing a minor problem with the Adobe Reader XI Program loaded on my computer.  When clicking the data fields on PDF versions of various forms to enter numerical or text information, a dialogue box with a small white X in a red circle on the left side of the title bar pops open and is titled:
    C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe
    There is another white X in a red circle symbol displayed in the message field of the dialogue box along with the following message:
    Windows cannot access the specific device, path, or file.  You may not have the appropriate permissions to access the item.
    There is also an “OK” Button displayed on the right side of the lower margin of the dialogue box.
    Although the dialogue box is repeatedly displayed whenever I click on a data field, the program still allows me to enter and save the numerical and text information that is entered in each data field.
    My computer is a Hewlett-Packard Envy 23-d034 TouchSmart All-In-One Desktop Personal Computer with a Windows 8.1 Operating System that has all applicable Important and Recommended Windows Updates installed.  The Adobe Reader XI Program is the latest version, Version 11.0.06, and I have confirmed that there are no updates for the program at this time.
    Could you suggest any recommended actions to correct this problem with the Adobe Reader XI Program?

    unfortunately no. i have a problem in my computer that doesn't let me do that.
    this is  th entire message though and it appears on the background of the program trying to load. all you can see is the frame of Rreader, and immediatly after that it shuts down

  • How to replace the string in a file

    Hi, I have a file which contains the following data
    File.dat
    <file>
    <filenum>
    W10
    </filenum>
    <hello>Heading </hello>
    </file>
    I need to replace the contents of file.dat
    database sequence value (for example xx_seq.nextval)
    Can some one please tell me how to search this <filenum>
    W10</filenum>
    and replace this with xx_seq.nextval
    and write the entire contents of the file to new file
    I am doing some thing like this
    suppose if my database value returns 11 from the above sequence then
    the output should be in file2.dat as
    <file>
    <filenum>
    11</filenum>
    <hello>Heading </hello>
    </file>
    declare f_in utl_file.file_type;
    s_in varchar2(10000);
    string1 varchar2(32000);
    x number;
    begin
    f_in := utl_file.fopen('SAMPLEDIR','input.txt','R');
    f_in1 := utl_file.fopen('SAMPLEDIR','input1.txt','W');
    select xx_seq.nextval into x from dual;
    loop
    begin utl_file.get_line(f_in,s_in);
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    EXIT;
    string1:= string1 || s_in;
    utl_file.put_line( (f_in1,s_in);
    end;
    end loop;
    utl_file.fclose(f_in);
    end;
    In this case it is reading and writing as it is, but unable to replace the sequence value
    Can some one please tell me how to do using replace function
    Thanks

    Hi, I have tried this but getting error
    step 1: create table test_dept(dno number, dname varchar2(20))
    insert into test_dept values(10,'10-Sourcing dept');
    insert into test_dept values(20,'20-Audting dept');
    insert into test_dept values(30,'30-Computer dept');
    select * from test_dept;
    DNO DNaME
    10     10-Sourcing dept
    30     30-Computer dept
    20     20-Audting dept
    step 2:
    create table test_web (name varchar2(60), xml_col xmltype) ;
    step 3:
    create sequence test1_seq start with 100 increment by 1
    step 4:
    test.out has the following contents (it is not .xml file) and i dont have <?xml version="1.0" ?> tag at the begining
    <File>
    <File_Type>Type1</File_Type>
    <File_Header_Record>
    <file_num>WP10</file_num>
    </File_Header_Record>
    <Transaction>
    <Transaction_Type>TR 1</Transaction_Type>
    <Amount>
    <Amounts>100</Amounts>
    </Amount>
    <Depts>
    <Dept_Type>Sourcing</Dept_Type>
    <Dept>10</Dept>
    </Depts>
    </Transaction>
    <Transaction>
    <Transaction_Type>TR 2</Transaction_Type>
    <Amount>
    <Amounts>200</Amounts>
    </Amount>
    <Depts>
    <Dept_Type>Auditing</Dept_Type>
    <Dept>20</Dept>
    </Depts>
    </Transaction>
    <Transaction>
    <Transaction_Type>TR 3</Transaction_Type>
    <Amount>
    <Amounts>300</Amounts>
    </Amount>
    <Depts>
    <Dept_Type>Computer</Dept_Type>
    <Dept>30</Dept>
    </Depts>
    </Transaction>
    </File>
    step 5:
    DECLARE
    v_check_file_exist BOOLEAN;
    v_file_length NUMBER;
    v_block_size NUMBER;
    v_file_path VARCHAR2 (100);
    v_file_name VARCHAR2 (100);
    v_file_type UTL_FILE.FILE_TYPE;
    v_str varchar2 (32760);
    v_cnt number;
    v_seq number;
    --check whether file exists and has data in it
    BEGIN
    v_file_path := '/usr/tmp';
    v_file_name := 'test.xml.out';
    -- initailise the variables
    v_cnt := 0;
    UTL_FILE.FGETATTR (v_file_path,
    v_file_name,
    v_check_file_exist,
    v_file_length,
    v_block_size);
    if v_check_file_exist
    then
    DBMS_OUTPUT.put_line (' File exists');
    IF v_file_length > 0 AND v_block_size > 0
    THEN
    BEGIN
    select test1_seq.nextval into v_seq from dual;
    insert into test_web values(v_seq,v_file_name);
    EXCEPTION
    WHEN NO_DATA_FOUND
    THEN
    DBMS_OUTPUT.put_line ('No data found '||SQLERRM);
    WHEN OTHERS
    THEN
    DBMS_OUTPUT.put_line ('others '||SQLERRM);
    END;
    commit;
    ELSE
    DBMS_OUTPUT.put_line ('No Data in File');
    END IF;
    ELSE
    DBMS_OUTPUT.put_line (' File Not Available');
    END IF;
    END;
    I am getting below error
    File exists
    others ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML
    processing
    LPX-00210: expected '<' instead of 't'
    Error at line 1
    My requirement is to replace the
    1. contents of the file WP10 from <file_num>WP10</file_num>
    with sequence value 'WP101' because sequence is starting at 100
    2. Replace all Dept tag <Dept>30</Dept> with Dname value from test_dept table
    for example
    <Dept>10</Dept> should be replaced with <Dept>10-Sourcing dept</Dept>
    update the
    when i say select * from test_web;
    It should contain this row
    101 <File>
    <File_Type>Type1</File_Type>
    <File_Header_Record>
    <file_num>WP101</file_num>
    </File_Header_Record>
    <Transaction>
    <Transaction_Type>TR 1</Transaction_Type>
    <Amount>
    <Amounts>100</Amounts>
    </Amount>
    <Depts>
    <Dept_Type>Sourcing</Dept_Type>
    <Dept>10-Sourcing dept</Dept>
    </Depts>
    </Transaction>
    <Transaction>
    <Transaction_Type>TR 2</Transaction_Type>
    <Amount>
    <Amounts>200</Amounts>
    </Amount>
    <Depts>
    <Dept_Type>Auditing</Dept_Type>
    <Dept>20-Audting dept</Dept>
    </Depts>
    </Transaction>
    <Transaction>
    <Transaction_Type>TR 3</Transaction_Type>
    <Amount>
    <Amounts>300</Amounts>
    </Amount>
    <Depts>
    <Dept_Type>Computer</Dept_Type>
    <Dept>30-Computer dept</Dept>
    </Depts>
    </Transaction>
    </File>
    Can you please check
    Thanks

  • Replace a string within text file to another string

    hi everybody
    i wich to replace some word writed in text file to another word,,,,for example i want to replace all word when the word is "SOLARIS" to "solaris" .
    anyone have an idea to resolve this prob via command or script,plz respond me.
    thanks

    To elaborate on alan.pae's response:
    sed 's/SOLARIS/solaris/g' oldfilename > newfilename
    -systemstate

  • Replace String within a file

    i want to replace a string within a file
    there is NO GUI ..
    i take in mind two approaches
    1) hold the file content in memory
    and rewrite the file
    2) write the new data to a new file.
    and then rewrite the original file
    any better ideas

    sorry, no..
    Your idea is kinda right if small file is within existance..
    Small file.
    Why not just use the filereader and filewriter? read the docs upon that
    Large file
    Why wont you create a string buffer, and parse the file chunk by chunk into that buffer one at a time. Then of course you saved the position of the character or word you wanted to apend or write, and you just write it back to that area.

  • How to save string in a file with special-chars

    Hello,
    i´m usingthe MD5-llb to create a password.
    Then i  want to save this MD5-string to a file and later read it back abd compare.
    Works perfect with one proplem:
    Some word create a "\r" in the MD5-string and when i save this string to a file and read it back then its read back as a "\n" so that the compare is not working.
    My question is: How can i save a string exactly like it is to somewhere and read it back (also invisible chars)
    For example the word: heinz
    is in MD5: \r\FB^\07\A6\07T\C7\D9\C2\94\AB\C9\1DS\95 (string indicator as codes display)
    when i save the string to a file then i rerad back: \n\FB^\07\A6\07T\C7\D9\C2\94\AB\C9\1DS\95
    I used the "write text file" and "read text file"
    What do i have to use to save and read the same?
    Thx
    Solved!
    Go to Solution.

    I believe an MD5 hash is 16 bytes long. Use the binary read and write file I/O functions and specify the length of the data to be read or written.
    Now is the right time to use %^<%Y-%m-%dT%H:%M:%S%3uZ>T
    If you don't hate time zones, you're not a real programmer.
    "You are what you don't automate"
    Inplaceness is synonymous with insidiousness

  • 3D string array to file

    How can I write a 3D string array to file?

    sascha:
    You could do this a lot of different ways.
    The first and most obvious thing that comes to my mind is that you can
    think about a 3D array as an array of 2D arrays. (For that matter a
    2D array is an array of 1D arrays.)
    Thus you could use a for loop to index your 3D array down to 2D and
    then perform multiple writes to write each 2D array "element" of this
    array of 2D arrays to disk. You would probably want to write some
    sort of header which defines how many dimensions there are in the
    array so that whatever reads it back later will have an easier time
    reading it back. (Otherwise you'd have to implement EOF handling for
    the read back portion.)
    To read it back you just use the same logic but build a 3D array using
    a 2D read inside a for loop.
    Dou
    glas De Clue
    LabVIEW developer (looking for a job...
    [email protected]
    [email protected] (SaschaS) wrote in message news:...
    > How can I write a 3D string array to file?

  • Get specific Strings from File

    Good morning to every one.
    I 've got a text file which contains a customer number and an order number, coded as we see in the picture below:
    I am trying to develop a tool in Visual Studio, which it reads the file line-by-line and fills a listbox, with the order_number and the customer number. From the file above, I know that the order number are the digits on the first 'column' after the leading-zeros,
    until '/', and the customer number are the digits without zeros in the 'third' column before 'CUSTOMER_NUMBER'. My form looks like:
    The problem is, that the number of before the fields in file, are not equal in every line.
    So, my question is how I can retrieve the 'order number' and 'customer number' from the text file and copy the results to list box, after clicking on 'Get Strings' button, like:
    359962656   2238914
    359562804   2238914
    etc...
    I attach my code here:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    namespace ReadStringFileApp
    public partial class frmMain : Form
    public frmMain()
    InitializeComponent();
    OpenFileDialog openfile = new OpenFileDialog();
    //openfiledialog to pickup filename
    private void btnFindFile_Click(object sender, EventArgs e)
    openfile.Filter = "Text|*.txt";
    if (openfile.ShowDialog() == DialogResult.OK)
    lbxResults.Items.Clear();
    txtFilepath.Text = openfile.FileName.ToString();
    //get strings from file
    private void btnGetStrings_Click(object sender, EventArgs e)
    //check if there is a file path on textbox
    if (txtFilepath.Text == "")
    MessageBox.Show("No File Select. Please select a file", "Error File Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnFindFile.Focus();
    return;
    //create list for all lines inside file
    List<string> lines = new List<string>();
    string line;
    using (StreamReader r = new StreamReader(@txtFilepath.Text))
    while ((line = r.ReadLine()) != null)
    string ordernum;//string for order number
    string customer;//string for customer number
    //line = ordernum + "\t" + customer; //concatenate results to fill the list box
    lbxResults.Items.Add(line);
    r.Close(); //close file
    private void btnExportToFIle_Click(object sender, EventArgs e)
    //check if listbox is empty
    if (lbxResults.Items.Count == 0)
    MessageBox.Show("Result List is empty! Choose a file to proceed.", "Error Result List", MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnGetStrings.Focus();
    return;
    //read listbox contents and parse to a list object
    List<string> list = new List<string>();
    foreach (String i in lbxResults.Items)
    list.Add(i);
    //Create a file in c: with results
    File.WriteAllLines(@"C:\export-test.txt", list, Encoding.Default);
    MessageBox.Show("File export completed!", "File Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
    Thank you in advanced

    @ Joel Engineer
    and@
    Val10
    I combined your responses and I get my results correctly. I attached the code I rewrite for further use:
    private void btnGetStrings_Click(object sender, EventArgs e)
    //check if there is a file path on textbox
    if (txtFilepath.Text == "")
    MessageBox.Show("No File Select. Please select a file", "Error File Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnFindFile.Focus();
    return;
    //create list for all lines inside file
    List<string> lines = new List<string>();
    string line;
    using (StreamReader r = new StreamReader(@txtFilepath.Text))
    while ((line = r.ReadLine()) != null)
    string order_customer;
    Regex reg = new Regex("0*");
    //set an string array, to split the file in columns positions, defining the characters
    string[] daneio = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    //get order number from the first column
    var ordernum_zeros = reg.Match(daneio[0]).Value;
    daneio[0] = daneio[0].Replace(ordernum_zeros, String.Empty);
    daneio[0] = daneio[0].Substring(0, daneio[0].IndexOf("/"));
    //get customer column, without zeros
    var customer_zeros = reg.Match(daneio[5]).Value;
    daneio[2] = daneio[2].Replace(customer_zeros, String.Empty);
    daneio[2] = daneio[2].Substring(0, daneio[5].IndexOf("CUSTOMER_NUMBER"));
    //combine the result in listbox
    order_customer = daneio[0] + "\t" + daneio[2];
    lbxResults.Items.Add(order_customer);
    r.Close(); //close file
    Thank you for your help!

  • Urgent: deleting a specific string form an existing .txt file

    Plz help me with a sample code on how to delete a specific string form an existing .txt file..it is very urgent...
    thanks in advance

    String path = "D:\\text.txt";
    File file = new File(path);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = "";
    String text = "";
    while((line = br.readLine()) != null) {
    text += line + "\n";
    br.close();
    String textToFind = "find";
    int start = text.indexOf(textToFind);
    if(start != -1) {
    text = text.substring(0, start) + text.substring(start + textToFind.length());
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(text, 0, text.length());
    bw.close();
    }

  • How to replace a string in a text file?

    Hi All,
    i read one text file and based on that i replaced the old character with the new string but it doesnt works.do any one of you have idea on this?
    My Code:
    String newPassword=(String) getInputText1().getValue();
    String password=(String)getSimNo().getValue();
    String sampleText = (String) getMobileNo().getValue();
    FileReader fr =new FileReader("c:/newLogin.txt");
    BufferedReader br =new BufferedReader(fr);
    String record=br.readLine();
    while (record !=null)
    String[] afterSplit=record.split(":");
    for (int p = 0; p < 1; p++) {
    String userName=afterSplit[1];
    String passWord=afterSplit[3];
    if(userText.equals(userName) && password.equals(passWord)) {
    passWord.replaceAll(passWord,newPassword);
    System.out.println("password: " + password +" changed to : "+ newPassword +" successfully");
    record =br.readLine();
    sample fiile in the text:
    userName:sebas:password:navin
    userName:sebas1:password:navin1

    All readLine does is copy a line of the file into a local variable. Change the copy as you will, the file won't change.
    You need to write a new version of the file, with the altered lines. Then, if required, you can delete the original file and rename the new file to the old file name.

  • Short dump while reading a currency field from Flat file into internal tabl

    Hi,
    I am getting a short dump........saying number conversion dump (while reading a currency value into field in internal table from a fixed lenght flat file).........
    Do I need to use a string variable to get the value from flat file or how ??
    Please suggest.

    Santosh,
    Thanks for your inputs,
    But my internal table type is of DEC (5,2) , I am getting that... it needs to be of type 'C'. Can you suggest.
    Ex :
    MOVE wa_temp-infile_string+106(8)  TO wa_item-QT_PERCENT
    This didnt work
    so i tried moving into a seperate variable
    MOVE wa_temp-infile_string+106(8)  TO v_percent.
    and then write to
    WRITE v_percent to  wa_item-QT_PERCENT.

  • Error while reading objects from a file

    Below is a short code to explain the problem i am facing
    i have been working on the same for past one week i am facing exceptions while reading a file containing more than one objects
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    * @author sakshi
    public class Storingobject implements Serializable{
        int x,y;
        public void addObject()
            //Storingobject temp;
            ObjectOutputStream objOut=null;
            try {
                objOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("temp.dat")));//if i pass true as parameter in FileOutputStream it gives Stream Corrupted exception
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
            try {
                // while((temp=objOut.writeObject(o))!=null)
                objOut.writeObject(this);
                System.out.println("Saved..");
                objOut.close();
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
        public void readobject()
            int i=1;
            Storingobject temp;
            ObjectInputStream objIn=null;
            try {
                objIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream("temp.dat")));
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
            try {
                while ((temp = (Storingobject) objIn.readObject()) != null) {
                    System.out.println("VAlues of object i++ :");
                    System.out.println("X: "+temp.x+"Y: "+temp.y);
            } catch (IOException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Storingobject.class.getName()).log(Level.SEVERE, null, ex);
        public static void main(String args[])
            Storingobject o1=new Storingobject();
            o1.x=10;o1.y=15;
            o1.addObject();
            o1.readobject();
    }

    //if i pass true as parameter in FileOutputStream it gives Stream Corrupted exceptionI agree. You can't append to a file written with an ObjectOutputStream. You would have to read it all in, write it all out again and write the new object. You're better off keeping the file open while you still have objects to write to it.
    while ((temp = (Storingobject) objIn.readObject()) != null) {ObjectInputStream.readObject() only returns null if you wrote a null. If you're not writing nulls, the correct technique is to loop until you get an EOFException. I don't favour explicitly writing a null just to get around this as suggested above, as it means you can never write a null for any other purpose.

  • How to search specific text/string in pdf files from command prompt?

    Hi,
    How to search specific text/string in pdf files from command prompt?
    Will be great if you can refer to any adobe provided command base utility to achieve the above target.
    Best Regards,

    You can't. The commandline parameters for Acrobat and Adobe Reader do not allow any type of commands to be run.

  • Replace string in a file

    I want a java program can replace string in a file with given string.
    for example,
    my file is
    abc 100
    aaa 110
    ded 123
    replace aaa with mmm.
    my codes is reading line by line and looking for aaa ,if read_line.index("aaa")> -1,then write mmm and aaa.substring
    Do you have ant other solutions?is there any file class method I can use?
    cheers.

    String content = <get file content>;
    String newContent = content.replaceAll( "aaa", "I get my homework on java.sun.com" );
    if( !newContent.equals(content) )
       <rewrite file contents>

Maybe you are looking for

  • Procedure giving error with collections

    H, i wrote a procedure in which i am using collections to out a some data.Its giving error. Below is format of procedure: Create or replace procabc(a in type_a, b in number, c out type_b) begin for i in 1....a.count loop for j in (select num from abc

  • Calling DTS package from Stored Procedure

    I am getting error calling DTS package from CF. So i want to call DTS package from SQL Server Stored Procedure. DTS package create text file. So no need of input or output parameter. What is the syntax?. thanks for ur help.

  • Error an exception with the type CX_SY_CONVERSYION_NO NUMBER Occurred

    Hi all I am trying to execute a demand report,which is of normal complexity,means some selections,new formulas, 2 variables,around 10 characteristics/Key figures. But this query thrwoing this error.and just disconnects from Bw server. with all users(

  • GR Slip output

    Hi MM experts.. I have configured GR/IR Slip print out,  where i have maintained the following settings. 1.OMBR- printer settings maintained( std printer LP01) 2.M706 out put type WE03 maintained 3.OMJ3 assigned plant sotrage loact to local printer L

  • Inbound procedure through XI

    Hi Experts, My requirement is like this ....I will get data either in file ot tab format from website through XI . I have to take the data from XI to SAP , make changes and send back to XI again. Can you please tell me the procedure, and also sample