Delete the specified character in a text file using RandomAccessFile

Hi All,
I have an invalid XML file which contains Return characters at the end of each line. I need to delete these return characters so the file becomes valid.
Does anybody have any idea how this could be done using RandomAccessFile?
I found joop_eggen's posting in this forum, modified it just a little and wanted to use it, but since the replacement character is "" (blank) it does not do what I need to.
The XML file looks like this:
<?xml version="1.0"?>
<EPMSObject>
<EPMSRecord><facilityname>KT0</facilityname><date_time>2007-06-01T00:00:00</date_time><devicetype>RPP</devicetype><devicename>RPP1A1_001.BCMF</devicename><meter>BCMF</meter><ckt_01_current>4.136000000000000e+000</ckt_01_current><ckt_02_current>0.000000000000000e+000</ckt_02_current><ckt_03_current>5.521000000000000e+000</ckt_03_current><ckt_04_current>0.000000000000000e+000</ckt_04_current><ckt_05_current>5.880000000000000e+000</ckt_05_current><ckt_06_current>0.000000000000000e+000</ckt_06_current><ckt_07_current>4.086000000000000e+000</ckt_07_current><ckt_08_current>0.000000000000000e+000</ckt_08_current><ckt_09_current>4.994000000000000e+000</ckt_09_current><ckt_10_current>0.000000000000000e+000</ckt_10_current><ckt_11_current>4.374000000000000e+000</ckt_11_current><ckt_12_current>0.000000000000000e+000</ckt_12_current><ckt_13_current>4.314000000000000e+000</ckt_13_current><ckt_14_current>0.000000000000000e+000</ckt_14_current><ckt_15_current>4.112000000000000e+000</ckt_15_current><ckt_16_current>0.000000000000000e+000</ckt_16_current><ckt_17_current>4.287000000000000e+000</ckt_17_current><ckt_18_current>0.000000000000000e+000</ckt_18_current><ckt_19_current>4.254000000000000e+000</ckt_19_current><ckt_20_current>0.000000000000000e+000</ckt_20_current><ckt_21_current>3.970000000000000e+000</ckt_21_current><ckt_22_current>0.000000000000000e+000</ckt_22_current><ckt_23_current>5.640000000000000e+000</ckt_23_current><ckt_24_current>0.000000000000000e+000</ckt_24_current><ckt_25_current>7.123000000000000e+000</ckt_25_current><ckt_26_current>0.000000000000000e+000</ckt_26_current><ckt_27_current>5.118000000000000e+000</ckt_27_current><ckt_28_current>0.000000000000000e+000</ckt_28_current><ckt_29_current>6.094000000000000e+000</ckt_29_current><ckt_30_current>0.000000000000000e+000</ckt_30_current><ckt_31_current>0.000000000000000e+000</ckt_31_current><ckt_32_current>0.000000000000000e+000</ckt_32_current><ckt_33_current>0.000000000000000e+000</ckt_33_current><ckt_34_current>0.000000000000000e+000</ckt_
34_current><ckt_35_current>0.000000000000000e+000</ckt_35_current><ckt_36_current>0.000000000000000e+000</ckt_36_current><ckt_37_current>0.000000000000000e+000</ckt_37_current><ckt_38_current>0.000000000000000e+000</ckt_38_current><ckt_39_current>0.000000000000000e+000</ckt_39_current><ckt_40_current>0.000000000000000e+000</ckt_40_current><ckt_41_current>0.000000000000000e+000</ckt_41_current><ckt_42_current>0.000000000000000e+000</ckt_42_current></EPMSRecord>
</EPMSObject>
Here is joop_eggen's code:
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class Patch {
  private static byte[] sought;
  private static byte[] replacement;
  private static boolean matches(MappedByteBuffer bb, int pos) {
    for (int j = 0; j < sought.length; ++j)
      if (sought[j] != bb.get(pos + j))
        return false;
    return true;
  private static void replace(MappedByteBuffer bb, int pos) {
    for (int j = 0; j < sought.length; ++j)
      byte b = (j < replacement.length)? replacement[j] : (byte)' ';
      bb.put(pos + j, b);
  private static void searchAndReplace(MappedByteBuffer bb, int sz) {
    int replacementsCount = 0;
    for (int pos = 0; pos <= sz - sought.length; ++pos)
      if (matches(bb, pos)) {
        replace(bb, pos);
        pos += sought.length - 1;
        ++replacementsCount;
    System.out.println("" + replacementsCount + " replacements done.");
    // Search for occurrences of the input pattern in the given file
    private static void patch(File f) throws IOException {
    // Open the file and then get a channel from the stream
    RandomAccessFile raf = new RandomAccessFile(f, "rw"); // "rws", "rwd"
    FileChannel fc = raf.getChannel();
    // Get the file's size and then map it into memory
    int sz = (int)fc.size();
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_WRITE, 0, sz);
    searchAndReplace(bb, sz);
    bb.force(); // Write back to file, like "flush()"
    // Close the channel and the stream
    raf.close();
    public static void main(String[] args) {
    String E_O_L;
    E_O_L = System.getProperty( "line.separator" );
    if (args.length == 0)
      args = new String[] { E_O_L, "", "C:\\GTI\\EPMSRecords.xml" };
    if (args.length < 3) {
      System.err.println("Usage: java Patch sought replacement file...");
      return;
    sought = args[0].getBytes();
    replacement = args[1].getBytes();
    //if (sought.length != replacement.length) {
      // Better build-in some support for padding with blanks.
      //System.err.println("Usage: sought (" + args[0] + ") and replacement (" + args[1] + ") must have same length");
      //return;
    for (int i = 2; i < args.length; i++) {
      File f = new File(args);
try {
patch(f);
} catch (IOException x) {
System.err.println(f + ": " + x);
Thank you,
Sinan Topuz

Thank you all.
Here is what I have right now and it works very well. It takes a couple of seconds to generate the second file and that satisfies me. I took the code sabre150 posted in this forum and changed it just a little bit, so thanks to him.
I hope this helps someone.
Sinan
import java.io.*;
public class SearchReplace{
    public static void main(String[] args){
        if(null == args || args.length < 2) {
           System.err.println("\nUsage: java <inputFileFullPath> <OutputFileFullPath> \nExample: java C:\\GTI\\Epmsrecord.xml C:\\GTI\\EpmsrecordNEW.xml");
           System.exit(1);
        Reader reader = null;
        Writer writer = null;
        try{
            char cr;
            char lf;
            char sp;
            int  indx;
            cr = '\r';
            lf = '\n';
            sp = ' ';
            indx = 0;
            reader = new FileReader(args[0]);
            writer = new FileWriter(args[1]);
            for (int ch = ' '; (ch = reader.read()) != -1;){
                indx++;
                if ( indx > 15 ) {      // Skip the first space character in <?xml version="1.0"?> otherwise the file becomes invaild!
                    if (ch != cr && ch != lf ) {
                        writer.write(ch);
                }else{
                    writer.write(ch);
            System.out.println("\nFile " + args[1] + " has been successfully created.");
        }catch(FileNotFoundException fnfe){
            System.out.println("\nError : File " + args[0] + " not found. Please make sure it exists and you have rights to access to it.");
        }catch (IOException e) {
            System.err.println("Caught IOException: " +  e.getMessage());
        }finally {
            try {
                if ( reader!=null ) {
                    reader.close();
                if ( writer!=null ) {
                    writer.close();
            }catch (IOException e){
                System.err.println("I/O error occured while trying to close the files.");
}

Similar Messages

  • How to display the out put of the sql query in a text file using forms

    I want to display the out put of the sql query in a text file using forms 6.0.Same could be done using spool command in sqlplus but i want it using forms....Fiaz

    Have a look at the text_io package:
    http://www.oracle.com/webapps/online-help/forms/10g/state?navSetId=_&navId=3&vtTopicFile=f1_help/oraini/c_text_io.html&vtTopicId=
    cheers

  • How to define special character in html text file used in loadvars

    Hi
    I'm witing some maths software and need to use the division
    sign in a text file which is loaded using LoadVars().
    The variable loaded is then assigned to a text area. Here's
    the variable example.
    &hint1=<title><b>Challenge 1: Instant recall
    of any table</b></title><p>Including table
    divisions eg 56 ÷ 8= </p>
    the division sign is missing or a just a box. I've already
    tried most options: &#x00F7; (which works in XML loaded to
    flash), &divide; %F7
    Can anyone help please?

    Hi Michael. Thank you for your reply.
    There is no declaration within sgm file itself - but while opening the file I use sgml application definition with the following settings:
    Default API client:  FmTranslator
    SGML character encoding:  ISO Latin1
    XML character encoding:  UTF-8
    Namespace: Enable
    CSS2 Preferences:
    Generate CSS2: Disable
    Add Fm CSS Attribute To XML: Disable
    Retain Stylesheet Information: Disable
    Entity locations
    Entity search paths
    C:\Program Files\Adobe\FrameMaker9\Structure\sgml\isoents
    So as you can see, character encoding is set to ISO Latin1 (there is no way to use UTF-8 encoding in sgml files)
    Typing ź or ć in sgm document and opening it with framemaker sgml application - I receive: ¿æ and message: "Non-SGML character found; should have been character reference"
    Everything works fine when I type f.ex.: &x016B; and insert appropriate reference lines into isolat1.rw and isolat1.ent files
    But what I would like to avoid is editing those isoent files each time new character is be needed.

  • How to read the last line in a text file using text_io?? please help

    Dear all
    I made a procedure that append text into a text file on the operating system.
    the text file grows rapidly. It contains now about 200,000 line . I need to read the last line only . In other wprds i need to go direct to the last line to read some values. Is it possible??
    Please help

    Hello,
    If you know the number of the line you want to read, I can sugget you to use the MORE dos command or the TAIL unix command that redirect to a temporary text file
    Example to create a file that contains the 200010th last lines :
    (Client)Host( 'MORE the_file_name.txt +200010 > small_file.txt') ;So you have only to read the small file with the TEXT_IO functions.
    Francois

  • How to delete the next character when typing text

    in windows you have a backspace and a delete which deletes forward, can that be done on the IPad?

    I'm sorry, but no. You can do this on a mac too by ctrl + D.
    http://store.apple.com/us/question/answers/product/MC184T/B/the-one-delete-key-m oves-left-is-there-a-singkeystroke-way-t…

  • How can I read a specific character from a text file?

    Hi All!
    I would like to read a specific character from a text file, e.g. the 2012th character in a text file with 7034 characters.
    How can I do this?
    Thanks
    Johannes

    just use the skip(long) method of the input stream that reads the text file and skip over the desired number of bytes

  • To read text file using utl_file

    I would like to read test_file_out.txt which is in c:\temp folder.
    create or replace create or replace directory dir_temp as 'c:\temp';
    grant read, write on directory dir_temp to system;
    then when i execute the below code i get the error .
    // to read text file using utl_file
    DECLARE
    FileIn UTL_FILE.FILE_TYPE;
    v_sql VARCHAR2 (1000);
    BEGIN
    FileIn := UTL_FILE.FOPEN ('DIR_TEMP', 'test_file_out.txt', 'R');
    UTL_FILE.PUT_LINE (FileIn, v_sql);
    dbms_output.put_line(v_sql);
    UTL_FILE.FCLOSE (FileIn);
    END;
    ERROR:
    invalid file operation
    i would like to use ult_file only and also can you let me know to read the text file and place its contents in tmp_emp table?

    Are you trying to read the contents of the file into the local variable? Or write the contents of the local variable to the file?
    Your text talks about reading the file. And you open the file in read mode. But then you call the UTL_FILE.PUT_LINE method which, as SomeoneElse points out, attempts to write data to the file. Since the file is open in read-only mode, you cannot write to the file.
    If the goal is really to read from the file, replace the UTL_FILE.PUT_LINE calls with UTL_FILE.GET_LINE. If the goal is really to write to the file, you'll need to open the file in write mode ('W' rather than 'R' in the FOPEN call).
    Justin

  • How to delete the specified line in file?

    How to delete the specified line in file? In case of deleting a specified line in a file, how to do?
    Line 1
    Line 2
    Line 3
    Line 4
    Line 5
    The case is a file including the above content. Now I wanna to delete the "Line 3" and how to realize the action in Java?

    An alternative solution can be :
    import java.io.LineNumberReader;
    import java.io.IOException;
    import java.io.File;
    import java.io.FileReader;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    public class LineDeleter {
    public static void main(String args[]){
    try {
    //suppose you want to delete line 3
         int lineToBeDeleted = 3;
         File f = new File("line.txt");
         long fileSize = f.length();
    //Wrap the FileReader with a LineNumberReader. It will help you
    //identify the lines.
    LineNumberReader lnr = new LineNumberReader( new FileReader(f));
    //Wrap the FileWriter object with BufferedWriter object. Create it with the buffersize
    //equal to the file size.
         BufferedWriter bw = new BufferedWriter(new FileWriter(new File("line1.txt")),(int)fileSize);
    //Wrap BufferedWriter object with PrintWriter so that it allows you
    //to print line by line
    PrintWriter pw = new PrintWriter(bw);
         String s=null;
         while ( (s=lnr.readLine())!=null ){
              System.out.println(s);
              int lineNumber = lnr.getLineNumber();
    //match the line number
              if(! (lineNumber==lineToBeDeleted)){
                   pw.println(s);
              pw.flush();
              lnr.close();
              pw.close();
         catch(Exception e){System.out.println(e);}
    If you want you can rename the line1.txt to the original file name.
    I hope this helps.Good luck!!!!!!

  • Delete specified line in a text file

    can anyone help me??
    how to remove specific line in a text file using java?? thank thanks

    Read the file, write a new one, and when you write skip over the line you want to delete.

  • Deleting a column in a text file using LabVIEW

    Hello all,
    I'm trying to delete the first column of my tab delimited text file using LabVIEW and then save it under the same file name.  Can someone show me a quick way to perform this operation.  Is this even possible with LabVIEW?  Any help would be much appreciated.
    My purpose is to automate this operation for hundreds of daily text files containing data that needs processing.  I'm currently using LabVIEW 8.2.
    Thanks!
    -noviceLabVIEWuser

    If the file is relatively small:
    Read the file using the Read from Spreadsheet File VI to get 2D array.
    Remove the column from the 2D array.
    Write out new 2D array to new file using Write to Spreadsheet File VI.
    If the file is relatively large then you will likely run into memory issues. In this case you will need to read the file in chunks. You can decide how many lines to read at a time. Use a for-loop that's set to run for the number of chunks to read (based on the total number of lines and the number of lines you want to read at a time). Hint: Quotient & Remainder function. In the loop use the Read Text File VI to read your set number of lines. Convert the lines to a 2D array delete your column, and write out that chunk of data to the new file. Rinse and repeat.

  • Removing the Control Characters from a text file

    Hi,
    I am using the java.util.regex.* package to removing the control characters from a text file. I got below programming from the java.sun site.
    I am able to successfully compile the file and the when I try to run the file I got the error as
    ------------------------------------------------------------------------D:\Debi\datamigration>java Control
    Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repet
    ition
    {cntrl}
    at java.util.regex.Pattern.error(Pattern.java:1472)
    at java.util.regex.Pattern.closure(Pattern.java:2473)
    at java.util.regex.Pattern.sequence(Pattern.java:1597)
    at java.util.regex.Pattern.expr(Pattern.java:1489)
    at java.util.regex.Pattern.compile(Pattern.java:1257)
    at java.util.regex.Pattern.<init>(Pattern.java:1013)
    at java.util.regex.Pattern.compile(Pattern.java:760)
    at Control.main(Control.java:24)
    Please help me on this issue.
    Thanks&Regards
    Debi
    import java.util.regex.*;
    import java.io.*;
    public class Control {
    public static void main(String[] args)
    throws Exception {
    //Create a file object with the file name
    //in the argument:
    File fin = new File("fileName1");
    File fout = new File("fileName2");
    //Open and input and output stream
    FileInputStream fis =
    new FileInputStream(fin);
    FileOutputStream fos =
    new FileOutputStream(fout);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(fis));
    BufferedWriter out = new BufferedWriter(
    new OutputStreamWriter(fos));
         // The pattern matches control characters
    Pattern p = Pattern.compile("{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;
    while((aLine = in.readLine()) != null) {
    m.reset(aLine);
    //Replaces control characters with an empty
    //string.
    String result = m.replaceAll("");
    out.write(result);
    out.newLine();
    in.close();
    out.close();

    Hi,
    I used the code below with the \p, but I didn't able to complie the file. It gave me an
    D:\Debi\datamigration>javac Control.java
    Control.java:24: illegal escape character
    Pattern p = Pattern.compile("\p{cntrl}");
    ^
    1 error
    Please help me on this issue.
    Thanks&Regards
    Debi
    // The pattern matches control characters
    Pattern p = Pattern.compile("\p{cntrl}");
    Matcher m = p.matcher("");
    String aLine = null;

  • I was given an assingment, but have no idea where to begin. The assingment is to create a text file using notepad with all of my digital inputs and some how make those imputs show up on my digital indicators on my control pannel

    I was given an assingment, but have no idea where to begin. The assingment is to create a text file using notepad with all of my digital inputs and some how make those imputs show up on my digital indicators on my control pannel.
    When it was explained to me it didn't sound to hard of a task, I have no LabVIEW experience and the tutortial sucks.

    StevenD: FYI, I did NOT give you the one star rating. I would never do that!
    StevenD wrote:
    Ow. Someone is grumpy today.
    Well, this is an assignment, so it is probably homework.
    Why else would anyone give HIM such an assigment, after all he has no LabVIEW experience and the tutorials are too hard for him?
    This would make no sense unless all of it was just covered in class!
    This is not a free homework service with instant gratification.
    OK! Let's do it step by step. I assume you already have a VI with the digital indicators.
    "...but have no idea where to begin".
    open notepad.
    decide on a format, possibly one line per indicator.
    type the document.
    close notepad.
    open LabVIEW.
    Open the existing VI with all the indicators.
    (are you still following?)
    look at the diagram.
    Who made the program?
    Does the code make sense so far?
    Is it a statemachine or just a bunch of crisscrossed wires?
    Where do you want to add the file read?
    How should the file be read (after pressing a read button, at the start of the program ,etc.)
    See how far you get!
    Message Edited by altenbach on 06-24-2008 11:23 AM
    LabVIEW Champion . Do more with less code and in less time .

  • How can we generate the reports in html or text file formats?

    Hi,
    Is there any package that can help in creating HTMLDB reports in .txt files or .html files? (Similar to TEXT_IO in Oracle Forms)
    How can we generate the reports in html or text file formats from HTMLDB?
    Thanks in Advance
    Renjith

    Hello all.
    Bi Publisher is great, but has a very high price tag. It's even more expensive than Forms & Reports Services. We are considering APEX to replace Forms & Reports on the web, but the reporting limitations are still a problem.
    I wonder if there is another option.
    Thanks

  • Report the size of all SharePoint Databases in a text file using PowerShell?

    I am new to Powershell. please help me for following question with step by step process.
    How to report the size of all SharePoint Databases in a text file using PowerShell?

    Hi Paul,
    Here is the changed script, which will also include the size for the Config DB.
    Please let me know if it worked:
    #Get SharePoint Content database sizes
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    $date = Get-Date -Format "dd-MM-yyyy"
    #Variables that you can change to fit your environment
    $TXTFile = "D:\Reports\SPContentDatabase_$date.txt"
    $SMTPServer = "yourmailserver"
    $emailFrom = "[email protected]"
    $emailTo = "[email protected]"
    $subject = "Content & Config Database size reports"
    $emailBody = "Daily/Weekly/Monthly report on Content & Config databases"
    $webapps = Get-SPWebApplication
    $configDB = Get-SPDatabase | ?{$_.Name -eq ((Get-SPFarm).Name)}
    $ConfigDBSize = [Math]::Round(($configDB.disksizerequired/1GB),2)
    Add-Content -Path $TXTFile -Value "Config Database size: $($ConfigDBSize)GB"
    Add-Content -Path $TXTFile -Value ""
    foreach($webapp in $webapps)
    $ContentDatabases = $webapp.ContentDatabases
    Add-Content -Path $TXTFile -Value "Content databases for $($webapp.url)"
    foreach($ContentDatabase in $ContentDatabases)
    $ContentDatabaseSize = [Math]::Round(($ContentDatabase.disksizerequired/1GB),2)
    Add-Content -Path $TXTFile -Value "- $($ContentDatabase.Name): $($ContentDatabaseSize)GB"
    if(!($SMTPServer) -OR !($emailFrom) -OR !($emailTo))
    Write-Host "No e-mail being sent, if you do want to send an e-mail, please enter the values for the following variables: $SMTPServer, $emailFrom and $emailTo."
    else
    Send-MailMessage -SmtpServer $SMTPServer -From $emailFrom -To $emailTo -Subject $subject -Body $emailBody -Attachment $TXTFile
    Nico Martens - MCTS, MCITP
    SharePoint 2010 Infrastructure Consultant / Trainer

  • Why does Preview automatically resize the text box to cut off the last character of added text? How do I fix it?

    Why does Preview automatically resize the text box to cut off the last character of added text? How do I fix it?
    I use the Tools > Annotate > Add Text feature, and when I click away after adding text, it automatically changes the text box size such that the last letter -- or last word -- gets bumped off into an invisible line below it, forcing me to manually adjust every single text box. It is highly annoying when trying to complete PDF forms (e.g. job applications).
    It appears to be a glitch, quite honestly, an error resulting from Apple's product design. Has it been fixed in the new operating system (for which they want $30)?
    I would very much appreciate any help you can provide! Thank you for your time.

    * "Clear the Cache": Tools > Options > Advanced > Network > Offline Storage (Cache): "Clear Now"
    * "Remove the Cookies" from sites that cause problems: Tools > Options > Privacy > Cookies: "Show Cookies"
    Start Firefox in [[Safe Mode]] to check if one of your add-ons is causing your problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    * Don't make any changes on the Safe mode start window.
    See [[Troubleshooting extensions and themes]] and [[Troubleshooting plugins]]

Maybe you are looking for

  • At a complete loss?

    Before anyone posts stuff about resetting to factory settings etc. or unplugging the modem, i have tried it all. Using a macbook pro and airport express.  Internet works great and fast when plugged directly into the modem however when trying to run w

  • MB 2.4 or "old" MBP 2.5 ... same price?

    I need to purchase a new Mac laptop for my 14-year old daughter. She would love the MB but the former top of the line MBP is basically at the same price at Amazon. What is the sensible thing to do? Old screen better, more expansion, speed similar (ri

  • Mapping of info-objects

    Hello Gurus, We are about to commence our new project DMS (Distributor Management System), where our secondary sales data will be brought into SAP BW and then we have an advantage of analysing them. We are now at the Blue Print stage, where we need t

  • Can not connect with itunes with iphone but can connect with same password with my computer

    I can not connect with Apple ID by IPhone but I can with same ID on my computer.

  • Unable to change my DP

    It's been 3weeks since my last DP. Changed and I don't knw why