Writing To A Specific Text File Line

In a program I am writing I need to be able to write to the end of a specific line in a textfile. I'm not sure of any particular way to do this apart from perhaps rewriting the whole textfile which would be a pain to do. Does anyone know of a simpler way of how to do this?

RandomAccessFile would help somewhat; with it you could overwrite at a given location by moving the file pointer. The problem with this is it still doesn't solve your case, which is appending. Files are essentially large arrays of data, so you can't easily insert data in the middle of it without having to rewrite the remaining portion of the file.

Similar Messages

  • Writing HTML data in TEXT File

    I am writing HTML content in TEXT file ...I read it in a string and then write using PrintStream...
    But it writes all content on one line ..I want to write it as it was in source HTML file...

    Perchance, the OP is referring to the lack of carriage returns in his outputted data, and querying where they have absconded to? An analysis of his posts to date reveals that he has read the contents of a File into a String variable, and wants to write the (presumably modified) String back to a file (uncertain as to whether this is the same file or a different one) In the process of outputting to said file, carriage returns previously contained in the original input file are not present in the output. I would hazard a guess that the OP does not want said carriage returns in the String to disappear.
    Is my analysis of the situation correct?
    An example of the code that you have written to date would be of extreme usefulness to us in aiding you in your noble quest.
    Without such a resource, I must rely on my intuition instead.
    Possible places that the carriage returns are being "dropped"
    1 - On reading in. Are you discarding carriage returns while building up your variable?
    2 - On manipulating. Are you processing this line by line, or reading it all into one large variable?
    3 - On output - are you using "print" or "println" in the output?
    I look forward to further correspondence with you sir
    kind regards,
    evnafets

  • Extra space in text file line

    This one is not critical, just aesthetical. My program writes lots of lines of info into a text file. One section of my code seems to include an extra empty space at the beginning of the line. The text is correct, but it just looks awkward being one space off from all the other lines of text.
    I will include a sample of the section of code writing to the text file. I didn't include all of my code, so parts of the sample I'm including will show errors, but you can get the gist of what I'm trying to do.
    In the line that displays "Start time of switch setting", the text is moved one spot over. Why?
    Amateur programmer for over 10 years!
    Attachments:
    space in first text file line - sample code.vi ‏28 KB

    Yup, that seemed to do the trick! I never even tinkered with "edit format string" of my "format into string" tools. I just wired my strings into them and let 'er rip.
    I ended up looking into the format of my other "format into string" tools in my program and they were set up the same - a space between each %s. But only that one "format into string" tool between string lines 5 and 6 did it actually place a space in the resulting text. Weird. Nowhere else did that occur.
    Thanks for the help!
    And tell me about desctructive kids!! I have 4 kids - all under the age of 6! I know all about toilets clogged by toys, lipstick smeared on walls, hand lotion all over just cleaned laundry, etc.
    My brother worked at a govt. contractor for a few years until he moved on to bigger and better. Years later he was browsing the stock section of the newspaper and he was reminded that he still had some stock from that company. So he glanced at the stock value listed in the paper and found he had almost $10,000 just sitting there! He bought a beautiful new Martin acoustic. I love that guitar! I have an old Fender dreadnought acoustic. I took it once to a guitar dealer to trade it in. He looked at it and handed it back and told me I better hold on to it, it was worth more than I realized.
    Probably not worth enough to put 4 kids through college though.
    Amateur programmer for over 10 years!

  • How to read the whole text file lines using FTP adapter

    Hi all,
    How to read the whole text file lines when error occured middle of the text file reading.
    after it is not reading the remaining lines . how to read the whole text file using FTP adapter
    pls can you help me

    Yes there is you need to use the uniqueMessageSeparator property. Have a look at the following link for its implementation.
    http://download-west.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/adptr_file.htm#CIACDAAC
    cheers
    James

  • How to read text file line by line...?

    how to read text file line by line, but the linefeed is defined by user, return list of string, each line of file is a item of list?
    please help me.
    Thanks very much

    Brynjar wrote:
    In Groovy, you would do something like:
    linefeed = "\n" //or "\r\n" if the user chose so
    lines = new File('pathtofile').text.split("${linefeed}")This is one of the things that has always annoyed me about Sun's sdk, i.e. the lack of easy ways to do things like that. You always end up making your own utilities or use something like Apache's commons.io. Same goes for jdbc and xml - I'll wait for appropriate topics to show how easy that is in Groovy :)I generally agree, but what I really don't like about the Groovy text-file handling niceties: They don't care about encoding/always use the default encoding. And as soon as you want to specify the encoding, it gets a lot more complex (granted, it's still easier than in Java).

  • Read from a text file line by line

    Hi,
    I am new to Labview and I am trying to output a text file line by line. For example if my text file is
    START
    SETRPM 1000
    WAIT 10s
    RAMP RPM linear,1000,2000,2 MAF linear,5,7,2
    WAIT 5s
    RAMP RPM sine,2000,1500,3 MAF sine,7,3,3
    END
    I want it to output
    START
    SETRPM 1000
    SETMAF 5 ...and so on
    I tried modifying this code provided by Altenbach but it is still not working as I want it to. Can anyone direct me toward how I can fix this?
    Thank you!
     

    Your program does exactly what you asked it to do.  In particular, it will repeat 10 times, at one per second, reading (and storing in String) the (unchanging) data that you bring in on the Shift Register.  This data will consist of the first line of the (assumed-)multi-line file you specified.
    I suppose your question is "Why is it only showing me one line?"  This is where it really pays to "Read the Directions Carefully" (or, in this case, carefully read the Help for Read from Text File).
    Bob Schor
    P.S. -- I pointed your code at a text file of 7 lines on my PC.  When I made a few small changes (including doing away with the silly For loop that shows the same thing over and over) , I got out an array, size 7, containing the lines of text.

  • Writing Records in a Text File to Specific Columns in the Text File

    Help Please! I am a noooooooooobbbbbb!
    I have searched this forum looking for a procedure that will write records from my database into certain col (positions) in a text file. Example:
    1234 TONY TEST 84889922 Y 34 TORCHCOMP 34
    5678 BOB JOHNS 43534534 N 56 SAFDWEERE 65
    I am thinking I would like to setup variaables like:
    Consumer_ID = Consumer(position 1,5)
    Name = name(position 10,20)
    Invoice_No = Invoice(position 30,40)
    etc.
    Any input will be greatly appreciated
    Thank You

    Hi,
    That's a formatting issue.
    Formatting is best done in the front end. For example, using SQL*Plus:
    COLUMN     consumer_id     FORMAT 9999     HEADING     c_id
    COLUMN     filler_6_9     FORMAT A4     HEADING     " "
    COLUMN     name          FORMAT A11
    COLUMN     filler_21_29     FORMAT A9     HEADING     " "
    COLUMN     invoice_no     FORMAT 9999999999
    SET     COLSEP          ""
    SET     PAGESIZE     9999
    SPOOL     x.dat
    SELECT     consumer_id
    ,     ' '          AS filler_6_9
    ,     name
    ,     ' '          AS filler_21_29
    ,     invoice_no
    FROM     table_x;
    SPOOL     OFFIf you have to do it in the back end, use functions like TO_CHAR and RPAD to make each part exactly the right length, then concatenate them all into one big string:
    SET     PAGESIZE     0
    SPOOL     x.dat
    SELECT     TO_CHAR ( consumer_id
              , 'fm99999'
              )          -- 1-5
    ||     '    '               -- 6-9
    ||     RPAD ( name
              , 11
              )               -- 10-20
    ||     '         '          -- 21-29
    ||     TO_CHAR ( invoice_no
              , 'fm9999999999'
              )          -- 30-40
    FROM     table_x;
    SPOOL     OFFEdited by: Frank Kulash on May 22, 2009 10:40 AM

  • Writing in between a text File

    Hi all,
    During a task, I am facing an interesting problem, this came first time since my 2 years development in Java.
    In always use
    BufferedReader in = new BufferedReader(new FileReader("/home/oracle/init1.txt"));
    to read from file and,
    PrintWriter opRpt = new PrintWriter ( new FileWriter("/home/oracle/init1.txt", true));
    to write to a file.
    This always works fine, but in the current task, I have to write in a text file,
    This file has e.g. 120 lines and I have to write after 36th line.
    So far, the suggestion I found is first to open text file (e.g. A),
    write first 36 lines to another file (e.g. B)
    then write new line to B,
    and then write remaining lines from A to B.
    Is there any easy way to do this job...
    Please guide me, I m in trouble.
    Thankx in advance.

    Please guide me, I m in trouble.No you're not; you already outlined a fine scenario how to accomplish this. If your file really contains just
    ~100 lines, an alternative would be to read the entire thing in core (the first part), add the new line(s)
    and read the rest of the file. Close the file and reopen it for writing again (effectively destroying its old
    contents) and write the new contents to the file again. An List containing all the lines of the
    file would do fine here.
    kind regards,
    Jos

  • Error writing path into a text file

    Latest edit to my text edit script is trying to remember the last opened file using a .txt "preference" file in a script bundle.
    Before I click run I edit the Pref file and put Default. I then click Open last. It then does what it should (alot like my other post) but gets an error at the last write in the script, writing the file path to the pref file. This is taken from the event viewer:
    write alias "Macintosh HD:Users:Richard:Documents:Other Text Files:Untitled.txt" to file "Macintosh HD:Users:Richard:Library:Scripts:Richard's Text Editor 3.scptd:Contents:Resources:Prefs:Save Location Pref.txt" as text
    Result:
    error "Can’t make alias \"Macintosh HD:Users:Richard:Documents:Other Text Files:Untitled.txt\" into type string." number -1700 from alias "Macintosh HD:Users:Richard:Documents:Other Text Files:Untitled.txt" to string
    Script here:
    display dialog "Open last saved or choose file" buttons {"Open last", "Open other"} default button 2
    if button returned of result is "Open last" then
    set val1 to (read POSIX file "/Users/Richard/Library/Scripts/Richard's Text Editor 3.scptd/Contents/Resources/Prefs/Save Location Pref.txt")
    if val1 is "Default" then
    EditFile("no")
    else
    EditFile(val1)
    end if
    else
    EditFile("no")
    end if
    on EditFile(val2)
    if val2 is "no" then
    set val3 to (choose file with prompt "Please select a .txt file:
    To save a text file as .txt in TextEdit, click 'Make Plain Text' in the Format menu and save the file.")
    --Get file path.
    else
    set val3 to val2
    end if
    if (get eof val3) is 0 then --Read doesn't like eof (end of file) to be 0 bytes.
    set val4 to ""
    else
    set val4 to read val3 --Read file before it gets erased.
    end if
    open for access val3 with write permission --Open file.
    set eof val3 to 0 --Erase file.
    repeat
    display dialog "Edit your text." default answer val4 buttons {"Revert", "Save"}
    set {val5, val6} to {text returned of result, button returned of result}
    if val6 is "Save" then
    write val5 to val3
    exit repeat
    else
    write val4 to val3
    end if
    end repeat
    --Write to file giving old data as default (to give the same affect as as read and edit).
    close access val3
    open for access POSIX file "/Users/Richard/Library/Scripts/Richard's Text Editor 3.scptd/Contents/Resources/Prefs/Save Location Pref.txt" with write permission
    set eof POSIX file "/Users/Richard/Library/Scripts/Richard's Text Editor 3.scptd/Contents/Resources/Prefs/Save Location Pref.txt" to 0
    write val3 to POSIX file "/Users/Richard/Library/Scripts/Richard's Text Editor 3.scptd/Contents/Resources/Prefs/Save Location Pref.txt" as text
    close access POSIX file "/Users/Richard/Library/Scripts/Richard's Text Editor 3.scptd/Contents/Resources/Prefs/Save Location Pref.txt"
    end EditFile
    Thanks, I can guess this is a simple fix like the others.

    Hmmm.
    First I checked it was all OK without POSIX and it works:
    display dialog "Open last saved or choose file" buttons {"Open last", "Open other"} default button 2
    if button returned of result is "Open last" then
    set val1 to alias (read file "Macintosh HD:Users:Richard:Library:Scripts:Richard's Text Editor 3.scptd:Contents:Resources:Save Location Pref.txt")
    --Read pref file to find out path of last edited file.
    if val1 is "Default" then
    EditFile("no")
    else
    EditFile(val1)
    end if
    else
    EditFile("no")
    end if
    on EditFile(val2)
    if val2 is "no" then
    set val3 to (choose file with prompt "Please select a .txt file:
    To save a text file as .txt in TextEdit, click 'Make Plain Text' in the Format menu and save the file.")
    --Get file path.
    else
    set val3 to val2
    end if
    if (get eof val3) is 0 then --Read doesn't like eof (end of file) to be 0 bytes.
    set val4 to ""
    else
    set val4 to read val3 --Read file before it gets erased.
    end if
    open for access val3 with write permission --Open file.
    repeat
    set eof val3 to 0 --Erase file.
    display dialog "Edit your text." default answer val4 buttons {"Revert", "Save"}
    set {val5, val6} to {text returned of result, button returned of result}
    if val6 is "Save" then
    write val5 to val3
    exit repeat
    else
    write val4 to val3
    end if
    end repeat
    --Write to file giving old data as default (to give the same affect as as read and edit).
    close access val3
    open for access file "Macintosh HD:Users:Richard:Library:Scripts:Richard's Text Editor 3.scptd:Contents:Resources:Save Location Pref.txt" with write permission
    set eof file "Macintosh HD:Users:Richard:Library:Scripts:Richard's Text Editor 3.scptd:Contents:Resources:Save Location Pref.txt" to 0
    write (val3 as string) to file "Macintosh HD:Users:Richard:Library:Scripts:Richard's Text Editor 3.scptd:Contents:Resources:Save Location Pref.txt" as text
    close access file "Macintosh HD:Users:Richard:Library:Scripts:Richard's Text Editor 3.scptd:Contents:Resources:Save Location Pref.txt"
    --Save path of edited file to pref file.
    end EditFile
    But change that 3rd line to:
    set val1 to alias (read file (path to resource "Save Location Pref.txt"))
    gets:
    Can’t make file (alias "Macintosh HD:Users:Richard:Library:Scripts:Richard's Text Editor 3.scptd:Contents:Resources:Save Location Pref.txt") into type file.
    P.S. Sorry bout question in answered post again.

  • How to check the content in a text file line

    hi all,
    i had the following problem:
    There is a text file with multiple lines of data in it
    The data comprises of characters, numbers and symbols
    In this file, any line can be commented (till the end) by using symbol ';'(semi-colon)
    Now i have to find the number of occurences of a symbol '$' in this data, such that
    it should not exist in a commented line
    One more limitation is that ';' (semi-colon) could occur at any position in a line, i.e., if this occured in the middle of the line, then all the following data in the line is taken to be as commented one and we have to skip it and move to next line.
    Plz do help.
    Regards,
    santosh
    Regards,
    santosh

    Hi santosh,
    just a guess this is what you need.
    Greets, Dave
    Message Edited by daveTW on 09-15-2006 09:59 AM
    Greets, Dave
    Attachments:
    search & count $.vi ‏13 KB
    search & count $.png ‏10 KB

  • Writing in to a Text file in Vista 32 OS

    Dear Friends,
    I have developed a standalone ticker in Adobe AIR, in that
    iam storing setting options in a local text file. It is working
    fine in XP.
    but when i install my application(ticker) in Vista32 OS,
    when i do changes in my setting file, i have to write the changes
    in local text file. it is not writing the modified setting text in
    the text file. my coding is:
    function writefile() {
    tempscr1=3;
    var finalstr2:String =
    "smallwinmode="+smscr+"&speed="+setmc.tickeropt.sld.s.value+"&alert="+altval+"&maxi="+max ifeed+"&alwtop="+setmc.tickeropt.aifch.selected+"&prescr="+tempscr1+"&prescrx="+newwindow3 .x+"&prescry="+newwindow3.y+"&firstinstal="+fins;
    var dskTopFileStream2:FileStream = new FileStream();
    var dskTopFile2:File = File.applicationDirectory;
    var fileString2:String = (dskTopFile2.nativePath +
    "\\settings.txt");
    dskTopFile2 = dskTopFile2.resolvePath(fileString2);
    dskTopFileStream2.openAsync(dskTopFile2, FileMode.WRITE);
    dskTopFileStream2.writeUTFBytes(finalstr2);
    dskTopFileStream2.close();
    Anybody can help me. if it works in Vista also i can release
    my product, i got struct up... kindly tell me should i change my
    coding to write txt file in Visa? pls help me....
    Thanks in advance,
    Syed Abdul Rahim

    Your user probably doesn't have permission to write to the
    application directory. The OS is right to protect the program
    directory.
    You should be writing data files into the user's home
    directory somewhere. All of the other "somethingDirectory"
    properties of File name such directories. For files that the user
    doesn't actually work with directly, I prefer
    applicationStorageDirectory myself. For files you are writing out
    for the user to see, I'd use documentsDirectory instead.

  • Reading multiple text files and writing them to one text file

    Hi,
    I'm trying to read a number of text files and write them to a single master file. My program reads all the files but only writes the last one to the master file.
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    // Input/Output Classes
    import java.util.Scanner;
    import java.io.PrintWriter;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.JTextArea;
    import java.awt.GridLayout;
    public class Actor implements ActionListener
    public static String DataRoot = "I:\\JAVA\\UBP\\DAT
    public static JFrame SW = new JFrame();
    public static JTextField txtSPath;
    public static JTextArea txtTable;
    public void actionPerformed( ActionEvent e )
    String Command = e.getActionCommand();
    if (Command.equals("Process") )
    SetupWin();
    ProcessAll();
    public void SetupWin()
    SW.setTitle("void");
    SW.setSize(300,400);
    SW.setLayout(new GridLayout(6,1));
    txtSPath = new JTextField(40);    SW.add(txtSPath);
    txtTable = new JTextArea(10, 40); SW.add(txtTable);
    SW.setVisible(true);
    public void ProcessAll()
    Process("Dunstable","Finance");
    Process("Dunstable","Production");
    Process("Dunstable","Sales");
    public void Process(String Town, String Dept)
    String SPath = DataRoot + Town + "
    " + Dept + ".txt";
    String MPath = DataRoot + "masterFile" + ".txt";
    txtSPath.setText(SPath);
    String message = "Trying  " + SPath;
    System.out.println(message);
    String SlaveTable=message;
    try// if following fails an exception is thrown
    Scanner Slave = new Scanner(new FileInputStream(SPath)); // reads slave file
    PrintWriter outputStream = null;
    outputStream = new PrintWriter(new FileOutputStream(MPath));
    while ( Slave.hasNextLine() ) // reads text line by line
    //Read and output next record
    String PartRecord  = Slave.nextLine();
    String FullRecord = Town + " " + PartRecord;
    System.out.println(FullRecord);
    outputStream.println(FullRecord);
    Slave.close();
    outputStream.close();
    txtTable.setText(SlaveTable);
    //An Exception Error would be THROWN by above & CAUGHT below
    catch(FileNotFoundException e)
    message = "Could Not Find " + SPath;
    System.out.println(message);     //console
    txtSPath.setText(message);     //window
    catch(IOException e)
    System.out.println("Slave I/O Problem " + SPath);
    }Edited by: Ardour on Mar 4, 2008 1:53 PM

    I haven't looked closely, but my spidey sense tingles at this:
    new FileOutputStream(MPath)This will clobber (erase) the previous contents of the file. Open in append mode:
    new FileOutputStream(MPath, true)Of course, if the file exists before you run this code, you will end up append to the original contents. If that is not wanted, consider using File's delete method first.

  • How do I read a text file line by line and store to array

    I have a text file, I want to be able to store each line of the file in an array, how would I go about doing this? code example? tutorial? Thank you

    Well, you got the pseudo code:
    a) read line
    b) add to array
    So whats the problem? What don't you know how to do?
    What does your text book tell you about reading files. I'm sure it has an example, every book I've read does.
    By the way I would use an ArrayList to store each line of text, that way you don't need to know in advance.

  • Reading a text file line by line and splitting each line into an array

    I have a text file that I want to read in line by line and within each line, I want to do some processing. I have a file like the following:
    apples||oranges||bananas||grapes
    cars||trucks||planes||boats
    And I want to end up with an array such that
    First...
    item(0) = apples
    item(1) = oranges
    item(2) = bananas
    item(3) = grapes
    Then move onto the next line with item getting cleared each time. Can anyone offer any ideas on how do to this? I am unclear on reading line by line and then also splitting into an array as I am new to this.
    Thanks.

    For reading a text file in line by line, you want to use a FileReader (java.io.FileReader)
    If you wrap it in a Buffered reader, you can call readLine() and get the file one line at a time.
      File file = new File("C:\myFile.txt");
      BufferedReader in = new BufferedReader(new FileReader(file));
      String s = in.readLine();
      while (s != null){
        // string handling here
        s = in.readLine();
      }For the second part, you probably want to look at the method String.split() which should split your string up into an array for you. Check out the API for java.lang.String
    Check out the

  • Writing data to a text file in a java code

    hey,
    can anybody tell me how can i enter data into a text file using java code.
    thanx

    yeah this is the proper answer....
    i had also a pblm ..that i had to read data from an excel sheet and write it to a File thru java code ....
    u can also use FileOutPutStream object....if u want...
    but there u can give newLine()..so all ur output will be in a single line to the file....
    bufferWriter.write(stringToBeWritten);
    bufferWriter.newLine();
    the stringToBeWritten can be a hardCoded string value..or any dynamic value like say fetching from database...

Maybe you are looking for

  • Multilingual support for BI Publisher reports

    Hi all, We are currently using BI Publisher APIs to generate reports. Our aim is to enable multi-language support for these reports.The translatable strings based on the locale are stored in xliff files. Using jedit, UTF-8 encoding is chosen as the d

  • I keep getting "Error 5002" When I try to buy an album. What do I do?

    I keep getting "Error 5002" When I try to buy an album. What do I do? I already reinstalled iTunes... not sure what this error means or how to be able to buy this album.

  • How to include javascript file (.js) to pages in portal

    Hi, I have been trying to include a javascript file (something.js) to a portal. actually, I want to include it on a html portlet that will be my navigation page. I have used the code below to add the js file, but it seems not working <script language

  • How can I validate the ejb-jar.xml against a downloaded ejb-jar_2_1.xsd

    I downloaded all configuration XML file schema, so we can point to the schema locally. (To be able to work even the network is not there.) I tried to change the xmlns, xmlns:xsi and xsi:schemaLocation in the root element of ejb-jar.xml file, I can't

  • Journal Entry Document List (Including Total Dr and Cr)

    Hi, Is there are report that I can run to give me all journal entries for a specified period, including the following information: User, Company Code, Document No., Doc type, Reference, Document Header, doc date, posting date and dr. and cr. values?