Overwriting Text Files?

I've got a program that writes text files ... cool. Up until now, I've been tagging the text file names with a time stamp so they don't overwrite each other between program runs. Now I'd like to (under certain criteria) actually overwrite some of these files.I know that I can overwrite the files simply by giving them the same name...(see implementation notes) ...but do I need to be concerned about the old file? ...like causing fragments or whatever?... I have a hard time imagineing that the code that writes (or in this case overwrites) the files will handle that.
Implementation notes: I basically, use a BufferedWriter chained to a FileWriter ... then I close it when Im finished.
BufferedWriter bw = new BufferedWriter(new FileWriter(myFileName));
bw.write("stuff");
bw.newLine();
bw.flush();
bw.close();

...but do I need to be concerned about the old file?No.
...like causing fragments or whatever?Yes, it probably will. No way around it.

Similar Messages

  • Avoid overwriting text file.

    i'm using a rather simple code to write stuff stored in an array to a text file. the only problem is every time i write new stuff to the text file it overwrites the previous file i had how do i stop this from happening.
    heres the code:-
    public void WriteToFile(){
                   // Stream to write file
              FileOutputStream fout1,fout2,fout3,fout4,fout5;          
              try
              fout1 = new FileOutputStream ("ItemName.txt");
              for(int f = 0; f<ItemNo;f++){
              new PrintStream(fout1).println (Item[f]);
                   fout1.close();
                   fout2 = new FileOutputStream ("ItemQuantity.txt");
                   for(int z = 0; z<ItemNo;z++){
              new PrintStream(fout2).println (Quantity[z]);
                   fout2.close();
                   fout3 = new FileOutputStream ("MaxQuantity.txt");
                   for(int w = 0; w<ItemNo;w++){
              new PrintStream(fout3).println (max[w]);
                   fout3.close();
                   fout4 = new FileOutputStream ("MinQuantity.txt");
                   for(int q = 0; q<ItemNo;q++){
              new PrintStream(fout4).println (min[q]);
                   fout4.close();     
                   fout5 = new FileOutputStream ("Charges.txt");
                   for(int q = 0; q<ItemNo;q++){
              new PrintStream(fout5).println (charges[q]);
                   fout5.close();     
              // Close our output stream
              // Catches any error conditions
              catch (IOException e)
                   System.err.println ("Unable to write to file");
                   System.exit(-1);
                   }

    Your code can be compressed ...
    public void WriteToFile(){
    // Stream to write file
    final String[] NAMES = {
      "ItemName.txt",
      "ItemQuantitiy.txt",
      "MaxQuantity.txt",
      "MinQuantity.txt",
      "Charges.txt"
    PrintStream[] outs = new PrintStream[5];
    try
      for (int i = 0;i < outs.length;i++) {
        outs[i] = new PrintStream(new FileOutputStream(NAMES, true)); // true is for "append" instead of "overwrite"
    for (int i = 0;i < itemNo;i++) {
    outs[0].println(Item[i]);
    outs[1].println(Quantity[i]);
    outs[2].println(max[i]);
    outs[3].println(min[i]);
    outs[4].println(charges[i]);
    catch (IOException ex) {
    // Error handling here
    finally {
    // Close all streams here

  • Write to text file; not overwriting old, but moving to next entry and writing

    I am interested in writing a series of filenames, to a text file, so I can keep track of sample ID and experiment #'s. I would like each new filename to be writtten following the previous filename, rather than always overwriting. I've done a brief check of some of the properties, and couldn't find anything. Any ideas? thanks

    Hey csmrunman,
     Just to clarify, are you looking to append text to an existing file without over-writing existing text, or are you looking to create a series of text files with unique names?  If you want to append text to an existing file, then Andrey's solution above should be what you need.  If you want to programmatically determine a unique name for the text files, then you can use a similar means to deterine a unique name (Andrey used the iteration terminal above so that each iteration of the while loop produces a unique text to be inserted into the text file).  You mentioned the use of sample ID and experiment number, which you could also use as a file name if you wish to, and even have the user of the VI enter the information that makes up the filename through front panel controls.  The string functions (in the Functions Palette under Programming » String) will be of great use here.  Of course, if you are just looking for an “out-of-the-box” solution, there is always the Write to Measurement File Express VI (Programming » File I/O), but this is best suited for situations where you have channels of data that you would like to store, so this may not fit depending on the data you wish to store.  If it does fit, however, there are settings that you can configure for saving to a series of files:
    Message Edited by Chris_G. on 09-28-2009 11:50 AM
    Chris_G
    Sr Test Engineer
    Medtronic, Inc.

  • Overwriting a part of a text file?

    Hi, i am writing an application where i can set markers on a waveform graph,
    now i want to write the values of the markers in a text-based file
    (spreadsheet) I make one file with several markers, but it happens that i
    want to overwrite a part of the text file, where a marker is, does anyone
    knows how to overwrite a part of a text file, with a VI with inputs of an
    offset and a length?
    Best regards,
    Thijs

    The "Write File" function has an offset input. The lenght written is the length of the data on input. First you open the file giving its path to "Open File", you write data at offset and "Close File". The previous content of the file at offset is overwritten.
    LabVIEW, C'est LabVIEW

  • Need help in Overwriting result in text file

    Sorry, im new to Labview.
    My situation is
    this.
    I can store the name and the result and i have the index.
    Now
    I'm having a problem on overwriting result i had in text file.
    I
    give you an example.
    Now in my text file i have a name of a
    student and the result.
    i wan to overwrite the result of the
    student.(this is just an example.)
    can someone guide me please?
    really
    need help as this is my school project.
    Thanks!
    i'll attach my program i have done soon.

    you got the wrong idea.
    i do not want to replace the file to a new file.
    what i want was to edit the exsiting file if the same name appear twice.
    Example:
    in my text file i have already had the name of example Tom and result 80
    and now i input the same name and diff result.
    i wan was to overwrite the result. 
    my project was similar to this here is my attachment of my project
    Attachments:
    LOCATOR.vi ‏19 KB
    TESTCAR.txt ‏1 KB

  • Partial Overwrite for text file

    I am trying to figure out how to overwrite a single line in a text file for an appointment program I am making. I am having a difficult time with this because I can't figure out how to overwrite a single line. If I could solve this, I could get my delete button (it's GUI) working and my edit button working. Thanks in advance!
    -Vegunks

    The short answer is that "overwriting" in a text file is problematic, and for a couple reasons:
    1. Often you want to replace 50 characters with 70 characters or 30 characters and you can't make a file simply grow or shrink like that.
    2. Your text encoding may have some surprises in store for you. Common encodings like UTF-8 can encode a single character as 1, 2 or three bytes depending on its value, so even if you think you are replacing 50 characters with 50 characters, you may be replacing 80 bytes with 84 bytes.
    The solution is to rewrite the entire file. More precisely:
    1. create a new file and write to it.
    2. delete the old file.
    3. rename the new file to take the place of the old file.
    edit: too slow!

  • Text file being overwrite when another info is save in he same text file

    At first, the text file is use for saving user information but after that when i want to save more thing in the same text file, the user infomration is being overwite. How can prevent the original message from being overwite?

    When you create the CFile/CNiFile object to write to the file, use the CFile::modeNoTruncate flag to indicate that you want to open the file as an existing file and that you don't want the file to be truncated to 0 length. For more information, see documentation for the CFile flags.
    - Elton

  • What is the best way of replacing words in a text file ?

    i want to read in a text file and when i come across a certain word, i want to change it to something else. Whats the best way to do this ?
    If i read in a line at a time, how would i only replace one word and not the rest of the line ?
    thanks

    thanks it works !!! But i wrote the contents to a new file.
    How do i overwrite the same file ? I put the the input and output file as the same location but it overwrites the original file with a blank one.
    i guess i have to write into another buffer and read all lines first before overwriting the file right ? how should i do that ?
    also, i only want to overwrite the file ONLY if applies replaceAll method, otherwise if no replacing takes place i dont want to keep updating the file everytime.

  • Write arrays into a text file in different columns at different times

    Hi,
              I have a problem write data into a text file. I want to write 4 1D arrays into a text file. The problem is that I need to write it at different time and in different column (in other word, not only append the arrays).
    Do you have an idea to solve my problem?
    Thank you

    A file is long a linear string of data (text). In order ro insert columns, you need to rewrite the entire file, because colums are interlaced over the entire lenght of the file.
    So:
    read file into 2D array
    insert columns using array operations
    write resulting 2D array to file again.
    (Only if your colums are guaranteed to be fixed width AND you know the final number of colums, you could write the missing columns as spaces and then overwrite later. Still, it will be painful and inefficient, because column data are not adjacent in the file.)
    LabVIEW Champion . Do more with less code and in less time .

  • How to write list values to a text file?

    Hi. Does anyone know how to write values stored in a List to a text file? I have a program that asks the user to enter a name and stores it in a list. The number of names in the list depends on how many times the user wants to enter a name. The problem is that my writeToFile method, which handles writing values to a text file, only writes one name and overwrites any previous names. How could I fix this so that it goes thru the list and writes every value to the file? Any hints would be appreciated!
    peace
    Chris
    import java.util.*;
    import java.io.*;
    public class StoreNames
    String name;
    char answer;
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    public void anotherName(List a)throws IOException
    System.out.println("Enter another name? (Y or N)");
    answer = (char)System.in.read();
    System.in.skip(2);
    while(answer == 'Y' || answer == 'y')
    inputName(a);
    System.out.println("Enter another name? (Y or N)");
    answer = (char)System.in.read();
    System.in.skip(2);
    if (answer == 'N' || answer == 'n')
    System.out.println("Ok. GoodBye");
    writeToFile(a);
    //prompts user to input names
    public void inputName(List a) throws IOException
    System.out.print("Enter a name: ");
    name = input.readLine();
    a.add(name);
    public void writeToFile(List a)throws IOException
    PrintWriter output = new PrintWriter(new FileWriter("names.txt"));
    output.print(name); //Problem area - handles only one line of input, overwrites previous input
    output.close();

    System.out is an instance of PrintStream (check the API documents for the System class to see this).
    So the easiest way to convert from a "print to screen" class to a "print to file" class is to acquire a PrintStream that prints to a file, and use it exactly the same as you'd have used System.out...
    So start with your console code...
            PrintStream out = System.out;
            for(int i = 0; i <10; i++){
                out.println("Number " +i);
            }Then you adapt to file code:
            FileOutputStream fos = new FileOutputStream("temp.txt");
            PrintStream out = new PrintStream(fos);
            for(int i = 0; i <10; i++){
                out.println("Number " +i);
            out.flush();
            out.close();Note that we flush the stream because for reasons of efficiency files aren't necessarily written to disk until you explicitly ask the system to do so (memory is fast, disks are slow, that's why).
    Closing the stream releases system resources associated with it.
    Actually, that's redundant, because close calls flush automatically, but I left it in for clarity.
    Any use ?

  • Writing dynamic value to a text file in Openscript

    How to write the dynamic values which i captured in a variable into a text file in openscript ? I searched throughout the user guide and i don't find any option for that. Please help, thanks in advance..

    One method using Export Table to CSV
    import oracle.oats.scripting.modules.basic.api.*;
    // Class DOMTable
    //export table content to a CSV file.
    public void exportToCSVFile(String filePath, boolean overWrite) throws AbstractScriptException, IOException
         {return;}
    DOMTable maTable = null;
    maTable.exportToCSVFile("c:\\temp\\export.csv", false);
    OR to read & write in a file
    Read a file & write in another file
    String MonFichierSource = "C:\\Documents and Settings\\jmarzolf\\My Documents\\Clients\\CD-APPS\\DataBank\\CD-APPS-SBL.csv";
    String MonFichierDest = "C:\\Documents and Settings\\jmarzolf\\My Documents\\Clients\\CD-APPS\\DataBank\\CD-APPS-SBL-2.csv";
    Scanner MonScanSrc = new Scanner(new File(MonFichierSource));
    FileWriter MonFichierDst = new FileWriter(MonFichierDest);
    while (MonScanSrc.hasNextLine()) {
    String MaLigne = MonScanSrc.nextLine();
    if (MaLigne.contains("ALL USER RESPONSIBILITY")) {
         MonFichierDst.write(MaLigne);
         MonFichierDst.write("\r");}}
    MonScanSrc.close();
         MonFichierDst.close();

  • How to update a text file?

    I am doing an assignment about a bank account. A text file stores the accounts.
    Account Text file:
    User1|Password1|Balance1
    User2|Password2|Balance2
    When user wants to deposit or withdraw the account, then how can update the balance.
    The problem is the length of balance is not fix. eg. $100 -> $90, vice versa.

    You cannot update a file that way. You're going to have to read the file and rewrite it in another file replacing the old balance value with the new balance value and then overwrite the old file with the new file.
    If the file is not to big you can load the whole file in memory with a String then work on that before rewriting it to the file.
    Otherwise your going to have to read chunks of lines and append them to a temporary file.
    I suppose this is no enteprise application but only a student's assignment, or else you should of course use a database for that kind of job!

  • Write into existing file with "write to text file"

    Hi all,
     I have a text file that contains several lines of data (text). Now I would like to replace the first three lines with text coming from a string array.
    My approach is shown in WriteToFile.vi that is attached.
    When I am executing this vi (with an empty file), everything seems to be working fine in the first place.
    The file will contain the following text:
    oneoneone
    twotwotwo
    threethreethree
    Now, when the third element in the array is shortened (lets say to "threethr") before execution,  the file will contain  the following text:
    (the file was not emptied before execution)
    oneoneone
    twotwotwo
    threethr
    three
    How can I avoid the last line being written? I have made many tests and I could not find a solution.
    One more example:
    Lets say we have an existing file, inside this file is:
    oneoneone
    twotwotwo
    three
    fourfourfour
    Now I would like to overwrite line three with "threethreethree". Therefore I execute my vi as shown in the attachment.
    What I get as a result is:
    oneoneone
    twotwotwo
    threethreethree
    ur
    So, the text in line four, which should not be touched, is "ur" instead of "fourfourfour".
    Any idea to solve this problem?
    What I basically need is replacing a line of a text file in a conveinient way.
    Thanks,
    Holger
    LV 8.5.1
    Attachments:
    WriteToFile1.jpg ‏17 KB
    WriteToFile.vi ‏11 KB

    The remaining fourth line is there because the third line has a <nl> at the end. You have not emptied the file so the rest of the file will be kept. This is because your line is shorter.
    In the scond example the third line is longer and it will overwrite the beginning of the fourth line.
    Files aren't organized in lines they are oganized in bytes. And what you write are bytes to the file even with text files.
    Replacing a single line in a file is done by reading the file line by line. All unchanged lines are written to a temporary file and the line with the new text will be written instead of the original line to the temporary file. When the writting is done rename the original file, then rename the new file into the original file and then delete the renamed original file.
    Waldemar
    Using 7.1.1, 8.5.1, 8.6.1, 2009 on XP and RT
    Don't forget to give Kudos to good answers and/or questions

  • How to write text file in acrobat javascript

    Hi,
    I need to write a txt file from acrobat javascript. How can i do this?
    My requirement is to get identity mail id and name? Using acrobat javascript i can able to take mail id as identity.email. I get the mail id as alert and in console
    How can i write this mail id to text file?
    Thanks in advance...

    Hi,
    here is a commented program stanza
    var v = this.getField("myTextField").value;
    // Get the contents of the file attachment with the name "MyNotes.txt"
    var oFile = this.getDataObjectContents("MyNotes.txt");
    // Convert the returned stream to a string
    var cFile = util.stringFromStream(oFile, "utf-8");
    // Append new data at the end of the string
    cFile += "\r\n" + v;
    // Convert back to a stream
    oFile = util.streamFromString( cFile, "utf-8");
    // Overwrite the old attachment
    this.setDataObjectContents("MyNotes.txt", oFile);
    // Read the contents of the file attachment to a multiline text field
    var oFile = this.getDataObjectContents("MyNotes.txt");
    var cFile = util.stringFromStream(oFile, "utf-8");
    this.getField("myTextField").value = cFile;
    [signature deleted by host]

  • Text file reading and writing problem

    Hello ! i am working on an electronic diary project and i am using Netbeans for that... i have finished all the rest but i am stuck into the saving of the appointments which i have been making.. i am using text files to save the entries ...what i am doing currently is that i am creating a file of every date which a user selects in the combobox.but if i want to add more appointment on the same date , then it overwries the previous one. i need to write something which can store multiple appointments in the same file.
    the writing code is:
    try {
    String aa = jTextField1.getText();
    String ab = jTextField2.getText();
    String ac =(String)jComboBox2.getSelectedItem();
    String ad =(String)jComboBox3.getSelectedItem();
    String ae = jTextField5.getText();
    String af =(String)jComboBox1.getSelectedItem();
    String ag = jTextArea1.getText();
    String outputFileName = ab+ac+ad+".txt";
    FileWriter outputFileReader = new FileWriter(outputFileName);
    PrintWriter outputStream = new PrintWriter(outputFileReader);
    PrintWriter outputStream1 = new PrintWriter(outputFileReader);
    PrintWriter outputStream2 = new PrintWriter(outputFileReader);
    PrintWriter outputStream22 = new PrintWriter(outputFileReader);
    PrintWriter outputStream3 = new PrintWriter(outputFileReader);
    outputStream.write(aa);
    outputStream1.write(ae);
    outputStream2.write(af);
    outputStream3.write(ag);
    outputStream.close();
    } catch (IOException e) {
    System.out.println("IOException:");
    e.printStackTrace();
    when i read the code , it doesnot reads the one which i store the text in new line...
    thanks

    Hi Dear
    Actually apending in your file is False so that it is overwriting this. do one thing open append option then it will add your data. for this just user true as the parameter with file name as i write in the below line. bedefault overwriting is false. you have to make this true.
    BufferedWriter out = new BufferedWriter(new FileWriter("Out.csv",true));
    try this your problem will solve.

Maybe you are looking for

  • How to find Oracle documentation in PDF format

    In the last month, i downloaded two oracle guide in PDF format from OTN site: "Oracle Spatial Topology and Network Data Models" and "Workspace Manager". But now I forgot the link where i founded a complete list of document prompted to download (over

  • How to access the attribute of child node

    Uday, now i have changed my coding as lr_node_contacts = wd_context->path_get_node( 'CUSTOMER.CONTACTS' ). lr_node_contacts->set_attribute( exporting name = 'EMAIL_ID'                                                 value = 'siva.palaniswamy' ). and

  • Weblogic deployment error

    I am trying to deploy a Very simple JFS Application that Connects to a Webservice and sends a request. When I run it in JDeveloper locally it works, but when i Deploy to Weblogic i get the following error: oracle/jrf/PortabilityLayerException [03:24:

  • Connecting Audio from DV1000 to TV

    Have a DV1000 Pavillion that I want to connect to Toshiba HD LCD TV. Has monitor cable but no HDMI. Connected monitor cable no problem. trying to figure what audio cable I need. TV manual shows a Y PC output to PC audio cable input. Would single male

  • Changing photo size

    I have some pictures on my ipod but when I look at them some are really blurry and have other weird stuff(they look fine on the computer). The others look fine, it seems only the big pictures are blurry, the small or meadium sized ones are fine. So m