Replace line

Hi there,
I am new to java. I want to find a specified line of string in the file, and then replace it with a new string. i would like to use RandomAccessFile. Could anyone here kindly give me an idea or show me a sample?
Thank you in advance,
bob

Just to give some details. First, the File object only encapsulates a file name and path, so it cannot be used to read or write data to the disk. To read / write, I recommend that you use a
// the following creates an object to read from a File
//  given a File object or a String with the path
FileInputStream fileIn = new FileInputStream(File file or String path);
// The following creates a FileOutputStream for writing
//  to the file, the wraps it with a PrintStream that
//  adds some useful methods
PrintStream fileOut = new PrintStream( new FileOutputStream(File file or String path) );In this way, you can use fileIn and fileOut exactly in the same way that yopu would be using System.in and System.out, which I assume you already used quite a lot ;)
Another approach, as you said, would be to use the RandomAccessFile, that keeps a FilePointer and allows both reading and writing. look at
http://java.sun.com/docs/books/tutorial/essential/io/rafs.html
for a tutorial about that.
Anyway, I expect that won't fit your needs, since it is not possible to "insert" or "cut" data from a file in this way. It would be only useful if the line you want to modify won't change its lenght... Wow, It looks like I can't explain myself properly, doesn't it?
What I mean is that a RandomAccessFile with the following file:
First Line - 123
Second Line - 456
Third Line - 789might allow you to change the "456" part to "654", since that is still 3 characters long. Yet you might not change "Second" to "2nd", since the number of character changes. If you did, the file would finish like this:
First Line - 123
2ndond Line - 456
Third Line - 789To do this, I'd say you did what someone else already said: Read the file line by line, change what you want, and save each line to a new File. Then, when you finished, delete the old file and rename the new one. If the file is small enough, you can do that on memory - just remember to use a StringBuffer instead of a String since it is much more efficient when it comes to 'growing' strings.
Hope this helps...

Similar Messages

  • Does CallerLineNumberAttribute replace #line directive?

    My understanding to
    #line directive  is to hardcode the line number in the code. But since after .net 4.5, we have
    CallerLineNumberAttribute.
    Can we ignore #line directive and mark it as a legacy skill?

    I am not sure if I understand your question properly but the #line directive lets you modify the
    compiler's line number.
    The CallerLineNumberAttribute allows you to obtain the line number in the source file at which the method is called at runtime. This not the same thing.
    So I guess the answer to your questions is: No, the CallerLineNumberAttribute does not replace #line.
    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question.

  • Replace line feed with perl

    I'm trying to replace 'line feed & space' with a line feed:
    perl -pi -e 's/\n /\n/g' ~/Desktop/scrap
    With no luck. Any help?

    I'm guessing this is related to line endings. If the file has legacy mac line endings it will behave as a single line. Try running the following. If it reports 0, then you'll need to convert the line endings:
    <pre style="border: 1px solid #ddd; padding-left: .75ex; padding-top: .25em; padding-bottom: .25em; margin-top: .5em; margin-bottom: .5em; margin-left: 1ex; max-width: 25ex; overflow: auto; font-size: 10px; font-family: Monaco, 'Courier New', Courier, monospace; color: #444; background: #eee; line-height: normal">wc -l < ~/Desktop/scrap</pre>
    The following will convert old mac line endings (as well as windows) to unix:
    <pre style="border: 1px solid #ddd; padding-left: .75ex; padding-top: .25em; padding-bottom: .25em; margin-top: .5em; margin-bottom: .5em; margin-left: 1ex; max-width: 40ex; overflow: auto; font-size: 10px; font-family: Monaco, 'Courier New', Courier, monospace; color: #444; background: #eee; line-height: normal">perl -pi -e 's/\r\n?/\n/g' ~/Desktop/scrap</pre>

  • Search and Replace String Function replaces line feeds when I only want spaces replaced?

    I need to replace every instance of a space or series of spaces in a multi line string with commas (or tabs) so I can dump it into a spreadsheet.
    I am using the regular expresion [\s]+ and it works but it is also replacing the end of lines (\r\n) too.
    How can I make it replace the spaces but leave teh end of lines intact?
    Solved!
    Go to Solution.
    Attachments:
    replace.vi ‏6 KB

    Right click on the search string and change it to '\' Code Display. Enter the space character (\s) correctly - you've got \\s right now.

  • How Can I replace line in text file

    I have a text file like following format
    1
    bvhhk
    g1
    2
    bvgjvh
    g1
    3
    mmm,mvb
    g2
    I want to replace 2 nd line to " prasad" and after replacing it should be following format
    1
    prasad
    g1
    2
    bvgjvh
    g1
    3
    mmm,mvb
    g2
    I try above change using following code segment and it is not work.
    static void modifyEmployeeDetails(String file_name){
    try{
         InputStreamReader reader= new InputStreamReader(System.in);
         BufferedReader buff=new BufferedReader(reader);
         FileReader read=new FileReader(file_name);
         BufferedReader buffer=new BufferedReader(read);
         FileWriter w=new FileWriter(file_name,true);
         PrintWriter write = new PrintWriter(w);
         System.out.print("Employee No : ");
         String No=buff.readLine();
    boolean eof = false;
    while (!eof) {
    String tep=buffer.readLine();
    if(tep.equals(No)){
    eof = true;
    System.out.print("Name : ");
    temp=buff.readLine();
    System.out.println("No");
    write.println(temp);
    System.out.print("Group No : ");
    temp=buff.readLine();
    write.println(temp);
    }catch(Exception e){
    System.out.println(e);
    Please correct If it is wrong and help me as soon as possible
    Thank you...............

    hi,
    I have a different approach of the solution to your problem.
    suppose you have entries in your file without any extra line feed between each two entries.
    the following program entirely reads your data into a bean list, changes a specific bean attribute and writes it to your data source.
    (you should adapt it to your needs)
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    public class FileReplace {
         public List<MyBean> readFile(BufferedReader in) throws IOException{
              String line;
              List<MyBean> beanList = new ArrayList<MyBean>();
              MyBean bean = null;
              int i=0;
              while((line=in.readLine())!=null){
                   if(line.trim().equals("***")){
                        beanList.add(bean);
                        i = 0;
                   }else{
                        switch (i) {
                        case 0:
                             bean = new MyBean();
                             bean.setAttribute1(line);
                             i++;
                             break;
                        case 1:
                             bean.setAttribute2(line);
                             i++;
                             break;
                        case 2:
                             bean.setAttribute3(line);
                             i++;
                             break;
                        default:
                             break;
              return beanList;
         public void writeToFile(List<MyBean> beanList, String outputFilePath) throws IOException{
              FileWriter out = new FileWriter(outputFilePath);
              for (int i = 0; i < beanList.size(); i++) {
                   out.write(beanList.get(i).toString());
              out.flush();
              out.close();
         public void test(){
              //BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              String filePath = "D:/file.txt";
              try {
                   BufferedReader in = new BufferedReader(new FileReader(filePath));
                   //read data
                   List<MyBean> beanList = readFile(in);
                   // edit a bean attribute
                   beanList.get(0).setAttribute2("prasad");
                   //write beans back to file
                   writeToFile(beanList, filePath);
              } catch (FileNotFoundException e) {
                   e.printStackTrace(); //handle appropriately this exception
              } catch (IOException e) {
                   e.printStackTrace();//handle appropriately this exception
              }catch (Exception e) {
                   e.printStackTrace();//handle appropriately this exception
         class MyBean{
              String attribute1;
              String attribute2;
              String attribute3;
              public final static int ATTRS_NUMBER = 3;
              public String getAttribute1() {
                   return attribute1;
              public void setAttribute1(String attribute1) {
                   this.attribute1 = attribute1;
              public String getAttribute2() {
                   return attribute2;
              public void setAttribute2(String attribute2) {
                   this.attribute2 = attribute2;
              public String getAttribute3() {
                   return attribute3;
              public void setAttribute3(String attribute3) {
                   this.attribute3 = attribute3;
              @Override
              public String toString() {
                   return attribute1+"\n"+attribute2+"\n"+attribute3+"\n***\n";
         public static void main(String[] args) {
              FileReplace instance = new FileReplace();
              instance.test();
    }hope it helps

  • Can't replace lines in a downloaded template doc

    there're two lines in my document that I can edit regularly, but they just swith right back if I try to scroll down or print it. Any suggestions?

    Are you talking about using Reader on a PDF or something completely different. Are you trying to replace a line or replace some text in a form?
    More details of what you are using and what you are trying to do wold be helpful.

  • How to Replace Line feed

    Hi All,
            i want to replace a line feed which is shown as ## in debug mode with space..
    Though i have tried replacing it by giving hexadecimal value of # but still its not gettign replaced.
    So how do i replace these occurences of line feed in the string which i am using..
    Regards,
    Syed

    Hi try this way :
    data: value type string....
    data: lv_feed type c value CL_ABAP_CHAR_UTILITIES=>CR_LF.
    replace all occurrences of lv_feed in value with space.

  • REPLACE RECORD or REPLACE LINE

    Hello gurus,
    I need hepl to solve this problem:
    The line with 00 is in a currency and the line with 10 is the same amount in EURO.
    00   Account1  Currency USD amount
    10   Account1  Currency EUR amount
    00   Account2  Currency AUD amount
    10   Account2  Currency EUR amount
    00  Account2   Currency USD amount
    10 Account2   Currency EUR amount
    I need the ABAP code to replace the line 00 with 10.
    Something like:
    if 00 write me 10.
    Thanks in advance,
    Ramona

    You can declare these as strings...or variables..
    and use REPLACE syntax to change values
    for example:
    Data: STR1(2) value  '00',
             STR2(2) value  '10'.
            STR(2)    value .
    REPLACE STR1 WITH STR2 INTO STR.
    WRITE:/ STR.
    orelse..
    write like this..
    if str1 = '00'.
    replace str1 with str2.
    endif.
    write:/ str1.
    Then the output of str1 will be '10'.
    Thanks
    Ram Ganji

  • Replace line in file

    Hi,
    does anybody know how to replace one line in a file with another line? I want to change only one line in a file and do not know how i can do it.
    Greetings.

    Would both the old and new lines be the samelength?
    No, they differ in length.Then you can't do it without create a whole new file.
    Read the old file.
    Spit the content of the old file into a new one.
    When you get to the line you want to change put the new line in instead of the old one...
    Continue on copying the lines from old to new.
    You CAN replace content in a file but if they have different length's you are SOL.

  • Find and Replace Lines

    I am running ID CS2. I have a document with several hundred lines, all the same size and justified left. I would like to do a find and replace and have the same lines replaced but centered. Every time I copy a centered line and do a replace, it replaces but not centered. Is there a way to do this?

    However, Find/Change SHOULD be able to handle this. Make sure that you've pressed the "more options" button to show the formatting options.
    Paste enough of the text into the find field to be sure it finds the right thing, then open the "find" format dialog and select the current alignment (remember, left aligned is not the same as left justified, which is justified text up to the last line, and then left align the last line). Leave the change field blank, and enter the new alignment option in the change options dialog.
    If you haven't already set up styles, this would be a good time to do it. You can use Find/change to apply the style instead of just changing the alignment.
    Peter

  • Replace Line Feed a field with imported data

    Hi, I’m trying to replace a line feed in a form field where data is imported to the field.
    I can make the replace function work when typing into the field, but I can’t figure out how to make it work on imported data.
    This is the script I use:
    if (xfa.event.newText.match(/[\n]/) )
    xfa.event.change = "LF"
    Regards,
    Kirstine

    Hi,
    So if I am getting you correctly, the imported data has the new lines (\n)?
    You could try the layout:ready event and test against the field's .rawValue. But this is going to be very inefficient.
    Niall

  • Successful 15" screen replacement (Line Issue)

    After purchasing a BTO PowerBook G4 15.2 1.67 DL, I quickly noticed the now well-known “white lines” issue. Initially, I called AppleCare, and sent my PB in for a depot-repair (with a copy of the “crankycat image” AND a copy of http://www.cameraid.com/art/quadrants.gif (found in this thread http://discussions.apple.com/thread.jspa?threadID=280560&tstart=45) . A week later, I received my PB with a note indicating “ Unable to duplicate issue). I then took my PB to my local Apple Store, and had one of their technicians look at it. After seeing the “Quadrants” image on my PB and looking at it on a 17” display model, the technician agree to take my PB in for repair. Today, I picked up my PB, thinking there was no way it would be repaired. However, the new screen DOES NOT display the line issue). To re-cap, I initially had a PB WITH the “line issue”, and now the same machine, with a new display, DOES NOT have the line issue. I really did not want to purchase the 17”, and was a bit apprehensive about purchasing one of the new MacBook Pro’s (I’ll wait until the 2nd Gen), so I am completely thrilled to now have a display w/o the line problem. So, I can confirm there are “line-less” 15” displays out there, from having seen both first hand.
    Thank You Apple Care...
    BTO PowerBook G4 15.2 1.67 DL   Mac OS X (10.4.4)  

    48K,
    Yes, I'm Sure. I checked with the "crankycat" and the "quadrants" images. It was pretty noticeable on my original screen, particularly if I dragged the images vertically one pixel at a time (esp. the quadrants). Just to make sure, I double checked the images on the display 15" models (each of which DOES have the "lines problem." On the new screen, the top two "quadrants" DO NOT shift at all, and the colors are identical. The bottom two "quadrants are slightly darker than the top two, but this also appears to be the case on EVERY screen I have tested (including the CRT on my Mac-Mini). Like I said, the top two do not shift at all (previously, the shades of grey DID shift).
    There are NO LINE at all doing the F11 "trick" on the new screen, but the old screen DID have the lines.
    I pressed the "Detect Display" button in Display Preferences, and made sure to choose "Color LCD." Note: it still has a magenta caste, but not as bad as the previous screen.
    Unfortunately, I didn't get a lot of time to talk to the tech (they were pretty busy). So, I don't have an answer to your question about a new batch of displays. I do know, they did replace the screen, and did NOT replace the logic board.
    My machine was in repair for about a week.
    I have owned this machine for slightly over a month. So, I was past the 14 day return policy.
    I DO have AppleCare (That Helped).
    dasein_geist

  • How to replace line break for comma

    Hi there,
    i have a string which is like
    header1,value1,header2,value2,header3,value3,header4,value4now i have to write the above string to a file which should be like
    file.txt should be
    header1,value1
    header2,value2
    header3,value3
    header4,value4i can write the string to a file easy, but i need to make the every even number , to line break.
    any help
    Thanks
    R

    You may get a better way, but this is how I would do this:
    -- split the string on comma
    -- iterate through the array using a for i+=2 loop and concatenate every pair of strings with comma-space between.
    db
    edit And write the results to a new array of half the length, of course. Then write the new array to the file.
    Edited by: Darryl.Burke

  • My Regular Expression is not replaceing lines with br / in them

    here is my problem
    This is my original Code:
    <p class="x3-subheading-1">DEGREE: Bachelor of Accountancy<br />MAJOR: Accounting</p>
    I want to find and replace all instances of this subheading class with this:
    <h3>******************</h3>
    This is what has worked for me for ones without <br />:
    Find:           <p class="x3-subheading-1">([^<]*)</p>
    Replace:      <h3>$1</h3>

    Managed to figure out this as a work arround.
    Find:          <p class="x3-subheading-1">([^<]*)<br />([^<]*)</p>
    Replace:     <h3>$1<br />$2</h3>
    Depending on the number of <br /> you can just add more
    Find:          <p class="x3-subheading-1">([^<]*)<br />([^<]*)<br />([^<]*)</p>
    Replace:     <h3>$1<br />$2<br />$3</h3>

  • Created extra line to be deleted

    Data in temp.ps after running my program is:
    % p +newText.map
    p +pfr.map
    p +pfu.map
    p +poa.map
    From my program, after each execution of the program, a line gets inserted into temp.ps after the line % p +newText.map. From my code the necessary is happening. But a line space is getting inserted each time as shown above.
    But I need as:
    % p +newText.map
    p +pfr.map
    p +pfu.map
    p +poa.map
    My code is:
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    public class updatetemp
         public updatetemp()
         public static void main(String args[]) throws IOException
              String new="InsertText";
              String Path="D:\\temp\\";
              mainclass(new, Path);
         public static void mainclass(String new, String Path) throws IOException 
              int val;
              char ch;
              File inputfile=new File(""+Path+"\\"+"temp\\temp.ps");
              File inputfileTmp=File.createTempFile(inputfile.getName(),"tmp");               
              BufferedReader br=null;
              BufferedWriter bw=null;
              String line;
              try
                   br=new BufferedReader(new FileReader(inputfile));
                   bw=new BufferedWriter(new FileWriter(inputfileTmp));
                   while((line=br.readLine())!=null)
                        if(line.startsWith("% p +newText.map"))
                                            line = LineChange(line,new);                                       
                        bw.write(line);                               
                        bw.newLine();
                        bw.flush();
              catch(IOException e)
                   System.out.println(e.getMessage());
              finally
                   try
                        br.close();
                   catch(Exception e)
                   try
                        bw.close();
                   catch(Exception e)
              if(inputfile.delete())
                   inputfileTmp.renameTo(inputfile);
         private static String LineChange(String line, String new)
                    String rep="";
              rep=line.replace(line,line+"\n\rp +"+new+".map");        
              return rep;
    }

    Input data consists of:
    [some lines of text]
    % p +newText.map
    [some lines of text]
    From my program, when it comes across the line % p +newText.map, it inserts a new line just below it. The insertion of the line is happening, but when I execute the program subsequent times, a line space gets inserted.
    What is it supposed to do if a line does not start with that String?
    The String % p +newText.map is constant in the input data
    Message was edited by:
    sony_tj

Maybe you are looking for

  • Digital Signature problem : Adobe forms

    Hi Experts, I am facing one issue in Adobe forms while implementing Digital Signature in one of the Custom Adobe form. I am following some steps as mentioned in the below link <link to blocked site removed by moderator> The problem is when I execute

  • Unfortunately Homescreen has stopped

    My phone just updated this morning, I don't know if it was a verizon update or an android update. Once it restarted, I am getting the message, 'Unfortunately, Homescreen has stopped.' When I click the 'OK' button, homescreen restarts and the massage

  • DW CS5 continually Acting Weird..

    Hi, Seems like for about 5 or 6 months, my DW will freeze up for a brief time.... "not responding" in other words. As this is the message thats displayed. Not only does this message display at the top of DW window, but in popup windows sometimes, for

  • How can I fix this in preview? (picture)

    This is a screenshot (command+shift+4) of the preview application.  Simple picture of a killer whale but there are those grey horizontal lines that appear and reappear as I zoom in and out.  If I don't zoom in or out and leave it still, it looks just

  • Simple maintanance scripts

    Upon discovering the power of cron, i have made scripts to clean & backup important files from my system. They are really bare bones & some stuff are missing, but could be usefull in an event of a total meltdown, and run some trivial cleanup commands