Write filename to the beginning of that file.

I need help on the following:
While reading and validating a file in Java, HOW can I
1. GRAB the FILENAME of the file I received,
2. Open the file and WRITE the FILENAME at the BEGINNING of the file?
Thank you in advanced.

You can get the filename by using java.io.File.getName();
As far as sticking it into the front of your file, you should read the whole old file (hopefully it's not too big), then write it all back out again to the same file, only write the name string first

Similar Messages

  • Writing filename to beginning of that file

    I need help on:
    While reading and validating a file in Java, how can I
    1. GRAB the FILENAME of the file I received,
    2. Open the file and WRITE the FILENAME at the BEGINNING of the file?
    Thank you in advanced.

    Here are the steps that you must do to accomplish what you wanted:
    1) grab the name of the file
    2) open a temporary file and write the file name obtained in #1 to the temporary file
    3) read the contents of the original file and write them to the temporary file
    4) close input file, flush the output file and close that as well
    5) delete the input file, and finally
    6) rename the tempoary file to the name obtained in #1 above
    Now the hard part is to do the actual coding!
    V.V.

  • How would I erase the beginning of a file?

    I want to be able to erase the beginning of a file, while writing to the end...WITHOUT reading the whole file and writing it again because that would be a waste of resourses. Obviously I know that option is available.
    My situation is that I am adding lines to a log file, and I want to remove any entries that are X hours old. Logging a lot of information would mean that every few seconds, an entry is older than X hours and needs to be removed. It doesnt have a set number of lines so I can't just recycle the file by doing something like: if at line number Y, start at line 1 and remember the current line number.
    Adding to the top of the file, pushing the others lines down, and making cuts at the end would also work, but the same situation arises, how do I add to the beginning of the file, without having to copy the entire file to add the entry to the top.
    The reason I don't want to read the whole file is because having to read the whole file and write the whole file when an entry is made is time consuming and wastes CPU and memory, especially when the logs are coming in several lines a second.

    I would think it could easily be done. say you want to erase the first 10 bytes, why cant you just say move the start of the file up 10 bytes. Somewhere in the filesystem the start of the file is stored. I found underlying file copying that claims this in FileChannel's transferTo and transferFrom:
    This method is potentially much more efficient than a simple loop that reads from this channel and writes to the target channel. Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.
    If I can't just chop, I'll have to copy quickly at scheduled intervals.
    This is code I ran to test the above quote:
        public static void main(String[] args) throws Exception{
            args = new String[2];
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter File Name:");
            args[0] = input.readLine();
            System.out.println("Enter test (0-2):");
            args[1] = input.readLine();
            long time = System.currentTimeMillis();
            int version = Integer.parseInt(args[1]);
            switch (version) {
                case 0:
                    BufferedReader in = new BufferedReader(new FileReader(args[0]));
                    PrintWriter out = new PrintWriter(new FileWriter("tempfile.txt"));
                    in.readLine();//skip line.
                    for (String line = in.readLine();line != null;line = in.readLine()) {
                        out.println(line);
                    in.close();
                    out.close();
                    break;
                case 1:
                    RandomAccessFile raf = new RandomAccessFile(args[0],"rw");
                    String line = raf.readLine();
                    long offset = raf.getFilePointer();
                    byte[] b = new byte[1024];
                    int bytes = 1024;
                    long index = 0;
                    System.out.println("index = " + raf.getFilePointer());
                    System.out.println("index = " + line.length());
                    while(bytes == 1024) {
                        bytes = raf.read(b);
                        index = raf.getFilePointer();
                        raf.seek(index - bytes - offset);
                        raf.write(b,0,bytes);
                        raf.seek(index);
                    raf.setLength(raf.length()-offset);
                    raf.close();
                    break;
                case 2:
                    RandomAccessFile raf2 = new RandomAccessFile(args[0],"rw");
                    String line2 = raf2.readLine();
                    long offset2 = raf2.getFilePointer();
                    FileChannel f = raf2.getChannel();
                    FileChannel g = f.position(0);
                    g.transferTo(offset2,raf2.length() - offset2,f);
                    raf2.setLength(raf2.length()-offset2);
                    raf2.close();
                    break;
            System.out.println(System.currentTimeMillis() - time);
        }and had these results
    166MB Log File
    Linux Mandrake 900Mhz
    Case 0 = 32914 ms
    Case 1 (1k byte[]) = 15043 ms
    Case 1 (16k byte[]) = 6988 ms
    Case 1 (1MB byte[] = 6113 ms
    Case 2 = 6188 ms
    :-/ guess this proves that the FileChannel can't chop

  • How to delete the beginning of a file?

    Hi,
    is there a way to delete the beginning of a file, or do I have to copy the rest of the file and create a new one and then delete the old one?
    Lets say my file contains "ThisIsMyFile" and I want to delete "This", so that my new file contains "IsMyFile", how can I do this?
    thanx

    You have to copy.

  • Appending "something" at the beginning of a file

    Hello,
    I am trying to append a character to the beginning of a file, doesnt seem to work with RandomFileAccess. I first called the seek() methond
    seek(0); //zero to send the file pointer to the front 
    write((byte) myCharValue);apparently it overwrites the value at the front instead of adding for example:
    before running the code the file has: "Java is Cool!"
    after running the code the file has: "xava is Cool!"
    Any Ideas?
    Thanks

    1. Create a new file.
    2. Write out whatever you wanted to insert at the beginning.
    3. Copy the data from the old file and append it to the new file.
    4. Close the files.
    5. Delete the old file.
    6. Rename the new file.

  • I cannot update or install updates on itunes. It says that the location for that file does not exist. I cant even uninstall itunes as the same error message comes up.

    I cannot update or install updates on itunes. It says that the location for that file does not exist. I cant even uninstall itunes as the same error message comes up.

    Hi vindog60,
    Thank you for using Apple Support Communities.
    To troubleshoot this issue where you get an installation error with iTunes on your Windows PC, please follow the steps in the article linked to below.
    Issues installing iTunes for Windows - Apple Support
    Cheers,
    Alex H.

  • Append a line at the beginning of a file via UTL_FILE

    Hello,
    is there a way to append a line to the beginning of a file instead of at the end of an existing file via UTL_FILE?
    Thanks in advance,
    Geert

    No, you would have to create a new file.

  • Xtra character appearing at the begining of a file written by my java pgm

    Hi,
    I am trying to write an object to an output file (which is a HTML document). But when the object is written at the
    begining of the file the following character appears
    ' �� '
    Is there a way to supress this character when the file is written ?
    My java program is running in a Sun Solaris machine and the file is created in the same directory.
    Thanks
    Bala.

    You have to give a lot more info... Are you trying to
    write the object as an object (ie serialize it) or are you
    simply trying to write the contents (data held in) this
    object to an HTML file? Some code would help too.....
    If you are simply wanting the contents written
    be sure you are not trying to use an ObjectOutputStream...
    If you are trying to write the Object (ie serialize it) then
    you have to remember that there are chances of
    non-printable characters being written...

  • Print data to the beginning of a file

    Hi,
    I have written this code to wite data to a textfile:
    PrintWriter FeedStream = new PrintWriter(new FileOutputStream(feed_path, true));
    FeedStream.println(text);
    FeedStream.close();The code works fine but it writes the data at the end of the file whereas I want it at the beginning of the file. How to solve this?
    Thanks in advance,
    leonard

    Well, the reason is that I want to print the data in another application and saving the data this way is more convenient.
    E.g.
    application 1 prints this to a file:
    L1 Test=45
    L2 Temp=10
    then the same application maybe has to write more data to the file at another time, and adding:
    L1 Test=39
    L2 Temp=12
    However application 2 that monitors the file every 6h should analyse the data from the newst to the oldest. For the conveniance when parsing the file with application 2 I want to add the data to the beginning of the file.

  • Is it possible to get the style, font and related info of a paragraph of a in design file and write it on the same in design file  on the  left side

    Is it possible to get the style, font and related info of a paragraph text  of a in design file and write  all the stuff on the same in design file  on the  left side with small fonts 
    as
    Lets  this is a text in in design file    :
    style : abc                      we are going to check the  condition  Agence Wallonne pour la Promotion d'une Agricultur we are going to check the  condition  Agence Wallonne pour la    font 12                                  d'une Agricultu we are going to check the  condition  Agence Wallonne pour la Promotion d'une Agricultu
    style : xyz                      we are going to check the  condition  Agence Wallonne pour la Promotion d'une Agricultur we are going to check the  condition  Agence Wallonne pour la    font 10                                  d'une Agricultu we are going to check the  condition  Agence Wallonne pour la Promotion d'une Agricultu

    Hi Poojith
    Not sure if this would solve your requirment but just in case might be helpful:
    1. We can mix up the HTML and HTMLB components in the JSP Page. However, can access only the HTMLB components in the controller. The following link refers to what customizations are offered by the HTMLB framework:
    [http://www.sapdesignguild.org/resources/htmlb_guidance/]
    2. Another option would be to use AbstractPortalComponents or a simple web app if that's feasible. (where custom UI themes, css and layout are more in control of the developers.)
    Thanks
    Deepak

  • Appending data to the beginning of a file

    How do you write data to the first line of a file without overwriting the data which is already present?
    Data before:
    888826759 100011021
    888826767 100011026
    888826916 100011024
    888826916 100011023
    888826940 100011029
    888826940 100011028
    888857389 100011020
    888871480 100011029
    What I want data to look like after:
    ABC
    888826759 100011021
    888826767 100011026
    888826916 100011024
    888826916 100011023
    888826940 100011029
    888826940 100011028
    888857389 100011020
    888871480 100011029
    I'm trying this, but it doesn't work as it overwrites the first piece of data in the file
    file.seek(0);              
    file.writeBytes("ABC");so that the output is:
    ABC826759 100011021
    Edited by: drakester on Oct 12, 2007 10:59 AM

    You might be able to write the file into one of the Collection Lists that maintain order (like LinkedList, but there are others), add the first line, and then rewrite the file from the list. You might also find the Collections methods reverse and rotate could be useful if you add the data at the end of the list.
    You could also create an array and fill the 2nd through last elements with the file lines, insert your data as the first element, then write the file from the array.
    Ther are a number of variations on the above approaches.

  • How can I determine the full path and filename of the currently opened .ai file?

    In Photoshop, right clicking the file name of the opened file in progress shows an option "Reveal in Explorer" so I know exacly where the file was opened from.
    In Lightroom, it is displayed in the metadata.
    New to illustrator, I have looked at loads of menu options get cannot see how to find this information.
    Would be grateful for some help.

    +1 for what Larry said if you are on OS X. You can then scroll through and select any of the listed items and when clicked upon it will take you to that folder/location.
    Not that it would offer ease of use or a better method, but you could also use a simple script to retrieve this info as another alternative method:
    Example Structure:
    alert("File Path/Location:\n" + File.decode(app.activeDocument.fullName));
    Results the Below Alert:
    alert("File Path/Location:\n" + File.decode(app.activeDocument.fullName).split('/').join('\n/ '));
    Results the Below Alert:
    But again, not that this approach would offer ease of use or a better method, just another alternative method (It works in my quick tests).

  • I get a message that itunes  has stopped working. When I check out why it is because of the dep security on my computer. When I try to find the program for itunes for the .exe file i cannot find it to turn off the dep for  that file

    I get a message that itunes  has stopped working. When I check out why it is because of the dep security on my computer. When I try to find the program for itunes for the .exe file i cannot find it to turn off the dep for  that file

    I found the file but when I added it to the  list for the Data  Execution Program to ignore , I received a message that the Program.x86/itunes file must have the DEP on in order to run. Anyone else having this problem ?

  • To add space at the begining of a file

    Hi,
      i have a requirement, when you transfer data to a file it should start writing data from 10th place.
    ex: data p_ext LIKE rlgrap-filename.
         data: var1(9)  type c value 'test data'.
         data: hold(100) type c.
         p_ext = '/devabap/if/daily/out/test1.rg'.
    open dataset p_ext for output in text mode encoding default.
    concatenate c_blank
                       var1
                       into hold
                       separated by cl_abap_char_utilities=>horizontal_tab.
    transfer cont to p_ext.
    close dataset p_ext.
    When i do this and check the file contents in AL11.
    i can see the contents like
    #test data.
    but i want to know how this can that be changed to like
                     #test data.
    Regards,
    Raghavendra.

    Hi ,
      When you use concatenate using separating , the separating string  does not come in the first place , it just comes between the values you are concatenating .
    so to acheive your result , you should again concatenate  cl_abap_char_utilities=>horizontal_tab , to your result before you transfer it to the file.
    concatenate cl_abap_char_utilities=>horizontal_tab cont into cont.
    or you can do is use the shift command after the concatenate operation.
    Here is a sample
    shift cont by 10 places RIGHT.
    Regards
    Arun
    Edited by: Arun R on Jan 22, 2009 1:29 PM

  • Insert a line into the beginning of a file without overwriting data

    I would like to dynamically alter/add new headers to a csv file as needed. The code I have below overwrites the previously written data an amount equal to each new header added each time I call the vi below. Any suggestions on how to do this without reading in the file each time? I want to avoid the processing time of reading in the file between processing new data.
    Thanks!
    Attachments:
    R900 - Log Data Stream to File.vi ‏22 KB

    Yes, but you can still write everytime, you dont need to read the file back.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

Maybe you are looking for

  • Text not displaying interactive widget

    By using the widget interactive activities, texts are cut or simply disappear. I tried to answer using pictures or even without. Same problem. Occurs randomly in different questions. I found another thread (https://discussions.apple.com/message/21621

  • How do I save all my e-mail folders on my own hard drive? (or keep copies)

    Firefox has been putting my older e-mails in TRASH without me asking; so I want to save all my incoming e-mail ON MY HARD DRIVE locally, as backup. Is this possible? IGNORE ALL THIS - it is YAHOO!Mail I need to deal with. My Mistake - SORRY !

  • URL to Specific Page in PDF

    I have to create a web page that has links to various pages within a single PDF. Links to PDFs open the document at page 1 by default. I have read that if you create a hyperlink like this, you can link to a specific page: http://www.somewebsite.com/s

  • Disks in RAID "Offline" - won't mount

    I can't get my mirrored RAID 1 array to mount. This comes after a forced shutdown. These are external firewire disks, daisy-chained, and hooked up to a G4's firewire port. The drives power up fine, show up in Disk Utility, and even spin up when I cli

  • Odd Charge to monthly bill

    On my billing statement for this month, I see I was charged 9.99 for a download on July 28th at 7:38am.  Not only was I driving to work at that time, I don't download apps to this phone, which is a much older phone than the smartphones in use nowaday