Over writing a file

I want to over write a file, so i used the following ways.
with Random Access file only
>>
RandomAccessFile r = new RandomAccessFile(fileName, "rw");
r.seek(seekIndex)
r.writedata..
r.close()
<<
with RandomAccessFile converted to DataOutputstream
>>
RandomAccessFile r = new RandomAccessFile(fileName, "rw");
r.seek(seekIndex)
// Get file descriptor from random access file and form file out put stream
FileOutpusStream fos = new FIleOutputStream(r.getFD())
BufferedOutputStream bos = new BufferedOutputStream(bos)
DataOutputStream dos = new DataOutPutStream(bos);
dos.writedata..........
dos.close()
r.close()
<<
second method is pretty fast when compared to first one.
but while executing the second code "some times" it is giving
"Bad File Number Exception"
I could not find any reason why it is giving this exception that to some times.
Please help me regard to do that.
and if there is any method to overwrite in an efficient way please let me know.
I searched about it and found java.nio is pretty fast. but pretty complex to use. so want to use data out put stream for this
tX
dL

I need to overwrite the file from some location(more clearly i have some junk data at end and want to over write it
with fair data) for that
I am using random access file to truncate that file and then open data output stream to append the data.
Even if we use Fileoutputstream to truncate i need to get File channel and truncate. Still the problem will be there.
* put the close in finally
* if u r killing the process have a systm to close the file first (i dunno of details gui or not ...)the advantage with this is even if there are exceptions then the close will be called. But if application got crashed
in the middle(say with kill -9) then finally wont be called so no closing of file.
I am trying to write some data in to file and i ll crash it, when the application gets invoked
again it has to over write last junk data and has to continue to write. thats why i am truncating the file to correct location
and trying to append my things. My program is not gui
Edited by: D_L_Kumar on Jan 8, 2008 11:10 PM

Similar Messages

  • Writing to files on windows

    Hi
    I have a jvm that will write some text to a file on a windows file system. There is some another process that will read it. This other process is beyond my control i.e. it wont be written by me and won't be java.
    How do i ensure that my jvm that writes to this file only when no other process is reading and also blocks on the write to prevent the other process trying to read when a write is in progress?
    I have read about FileChannel and FileLock and have tried writing a test app. My FileChannel tryLock call always seems to succeed, meaning that my write then goes ahead even when the other process is reading, which can cause this read to then fail.
    Any ideas? I know there are lots of hits for FileChannel and FileLock on this forum but nothing matching my requirements that i can see.
    appreciate any advice
    thanks

    Locks tend to be [advisory versus mandatory|http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html], so unless both processes are using locks, they don't work.
    One way to keep the reader from reading while you are writing is to write to a different fille in the same folder (say fileXXXXXXXX.tmp) then when you are done writing, rename it (say fileXXXXXXXX.txt).
    To keep from over-writing the file while another process is reading an earlier version.... hmmm.. include a unique timestamp in the name of the file?

  • Need help writing to file

    I have an ArrayList of XML strings. I am trying to write the XML strings in the arraylist to a text file. However, the only XML string that I see in the file is the first string repeated over and over. It is the only one getting to the file for some reason. I have tried the code below:
        public void writeToLogFile(String logFile, String msg) {
                try{   
                    FileWriter WriteFile = new FileWriter(logFile, true);  
                    BufferedWriter WriteBuff = new BufferedWriter(WriteFile); 
                    WriteBuff.write(msg+"\r\n");
                    WriteBuff.close(); 
                    WriteFile.close(); 
                }catch(IOException e) {
                    System.out.println("Error writing to file.");
    //        try {
    //            FileWriter fw = new FileWriter(logFile,true);
    //            PrintWriter pw = new PrintWriter(fw);
    //            pw.println(msg);
    //            pw.close();
    //        }catch(IOException ioExc) {
    //            System.out.println("error writing file");
        }  I tried the commented out code also. I've also tried using PrintStream. They all seem to give me the same result. My first thought was maybe I'm sending the same string to the method over and over but I'm not. If I loop through my arraylist of XML strings and do a System.out.println() instead of writing to file, I see that I am sending in different XML strings.
    Here's how I'm looping through the arraylist of XML strings call "al":
                for(int i=0; i<FileValues.length; i++) {
                    al = adapter.executeQuery(FileValues[0]);
    System.out.println("Writing to output file...");
    for(int x=0; x<=al.size()-1; x++) {
    //System.out.println(al.get(x).toString());
    test.writeToLogFile("c:/temp/a/limAdapterOutput", al.get(i).toString());
    System.out.println("Finished writing to output file.");
    What I'm doing is reading an arraylist (FileValues) of query parameters. For each parameter, I am querying a database based on the parameter and returning an arraylist of XML strings containing the query result. For each paramter, I'm returning about 1200 XML strings in the arraylist. Then I try to loop through the arraylist and write the XML strings to a file. However, this is when I run into my problem.
    Any ideas what's going on and how I can correct the problem? Thanks.

    for(int i=0; i<FileValues.length; i++) {
    al =
    al =
    al = adapter.executeQuery(FileValues[0]);
    System.out.println("Writing to output
    iting to output file...");
    for(int x=0; x<=al.size()-1; x++) {
    //System.out.println(al.get(x).toString());
    test.writeToLogFile("c:/temp/a/limAdapterOutput",
    ut", al.get(i).toString());
    System.out.println("Finished writing
    inished writing to output file.");
    When you write to the log file in the inner loop, it sounds like you want to use the x loop counter, not the i counter from the outer loop.  You comment out the print to System.out, which uses the x loop counter.  Why don't you do the same thing in the uncommented code?  Hard to follow exactly what you're doing, but maybe that will fix it.

  • Error while writing to file: C: \ Program Files (x86) \ iTunes \ iTunes.Resources \ el.Iproj \ iTunesExtrasDownload.png. Make sure you have access to this directory.

    When i try to install iTunes in my Windows 7, this error message apear "Error while writing to file: C: \ Program Files (x86) \ iTunes \ iTunes.Resources \ el.Iproj \ iTunesExtrasDownload.png. Make sure you have access to this directory." Someone help me!!

    That one's consistent with disk/file damage. The first thing I'd try with that is running a disk check (chkdsk) over your C drive.
    XP instructions in the following document: How to perform disk error checking in Windows XP
    Vista instructions in the following document: Check your hard disk for errors
    Windows 7 instructions in the following document: How to use CHKDSK (Check Disk)
    Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors, or use chkdsk /r (depending on which way you decide to go about doing this). You'll almost certainly have to schedule the chkdsk to run on startup. The scan should take quite a while ... if it quits after a few minutes or seconds, something's interfering with the scan.
    Does the chkdsk find/repair any damage? If so, can you get an install to go through properly afterwards?

  • I receive the following error message when trying to install QuickTime for Windows "Error writing to file C:/Program Files/QuickTime/QTSystems/QuickTimeCheck.ocx. Verify that you have access to that directory."

    I recieve the following error message when trying to install Quicktime for Windows "Error writing to file C:/Program Files/QuickTime/QTSystems/QuickTimeCheck.ocx. Verify that you have access to that directory."  I just trying to get the latest version of iTunes.  Thanks

    "Error writing to file C:/Program Files/QuickTime/QTSystems/QuickTimeCheck.ocx. Verify that you have access to that directory."
    That one's consistent with disk/file damage. The first thing I'd try with that is running a disk check (chkdsk) over your C drive.
    XP instructions in the following document: How to perform disk error checking in Windows XP
    Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors, or use chkdsk /r (depending on which way you decide to go about doing this). You'll almost certainly have to schedule the chkdsk to run on startup. The scan should take quite a while ... if it quits after a few minutes or seconds, something's interfering with the scan.
    Does the chkdsk find/repair any damage? If so, can you get an install to go through properly afterwards?

  • When downloading the new 10.7 update for itunes, an error message saying that there is an error writing to file, verify that you have access to this file comes up... what is this??

    When downloading the new 10.7 update for itunes, an error message saying that there is an error writing to file, verify that you have access to this file comes up... what is this??

    That one's consistent with disk/file damage. The first thing I'd try with that is running a disk check (chkdsk) over your C drive.
    XP instructions in the following document: How to perform disk error checking in Windows XP
    Vista instructions in the following document: Check your hard disk for errors
    Windows 7 instructions in the following document: How to use CHKDSK (Check Disk)
    Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors, or use chkdsk /r (depending on which way you decide to go about doing this). You'll almost certainly have to schedule the chkdsk to run on startup. The scan should take quite a while ... if it quits after a few minutes or seconds, something's interfering with the scan.
    Does the chkdsk find/repair any damage? If so, can you get an install to go through properly afterwards?

  • Itunes will not install. I get the error message "Error writing to file: C:\Program Files\Common Files\Apple\Mobile Device Support\com.apple.IE.client_main.dll     Verify that you have access to that directory."

    Itunes will not install. I get the error message "Error writing to file: C:\Program Files\Common Files\Apple\Mobile Device Support\com.apple.IE.client_main.dll     Verify that you have access to that directory."

    That one's consistent with disk/file damage. The first thing I'd try with that is running a disk check (chkdsk) over your C drive.
    XP instructions in the following document: How to perform disk error checking in Windows XP
    Vista instructions in the following document: Check your hard disk for errors
    Windows 7 instructions in the following document: How to use CHKDSK (Check Disk)
    Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors, or use chkdsk /r (depending on which way you decide to go about doing this). You'll almost certainly have to schedule the chkdsk to run on startup. The scan should take quite a while ... if it quits after a few minutes or seconds, something's interfering with the scan.
    Does the chkdsk find/repair any damage? If so, can you get an install to go through properly afterwards?

  • I'm trying to install the new version, but each time during the installation, "Error writing to file: C:/Program Files (x86)/Common Files/Apple/Mobile Device/Support/AppleMobileDeviceHelper.resources/Info.plist." Keeps popping up. What am I doing wrong?

    I'm trying to install the new version, but each time during the installation, "Error writing to file: C:/Program Files (x86)/Common Files/Apple/Mobile Device/Support/AppleMobileDeviceHelper.resources/Info.plist." Keeps popping up. What am I doing wrong?

    That one's consistent with disk/file damage. The first thing I'd try with that is running a disk check (chkdsk) over your C drive.
    Windows 7 instructions in the following document: How to use CHKDSK (Check Disk)
    Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors, or use chkdsk /r (depending on which way you decide to go about doing this). You'll almost certainly have to schedule the chkdsk to run on startup. The scan should take quite a while ... if it quits after a few minutes or seconds, something's interfering with the scan.
    Does the chkdsk find/repair any damage? If so, can you get an install to go through properly afterwards?

  • Error message while instilling. ''Error writing to file: C:\Config.Msi\5ad33.rbf. Verify that you have access to that directory

    I tried instilling 11.0.2 and couldn't and had to go thought tools and download only now I am instilling it got over half way and i get the error message ''Error writing to file: C:\Config.Msi\5ad33.rbf. Verify you have access tothat directory'' What do I do?????

    Are you running Kaspersky security software on that PC? (There's been a few reports in recent times of Kaspersky interfering with iTunes installs, with that message being produced.)
    If there is Kaspersky on board, we should try some general-principles getting-past-security-software-interference troubleshooting.
    Download and save a fresh copy of the iTunesSetup.exe (32-bit installer file) or iTunes64Setup.exe to your Hard drive. (Don't run the install on line, and don't start the install just yet.)
    http://www.apple.com/itunes/download/
    Restart the PC. After the PC restarts do not open any applications. Disconnect from your network and/or the internet. Now switch off all your security software (firewall, antivirus, antispyware).
    Now start the install by doubleclicking the iTunesSetup.exe (or iTunes64Setup.exe) file you downloaded earlier.
    Reenable all security software prior to reconnecting to your network and/or the internet.
    Any better luck with the security software shut down?

  • I am getting an error writing to file: C:\Program Files\iTunes\iTunes Resouirces\pl.lproj\AppletVStream.nib\objects.xib. Verify that you have Access to that directory.

    has anyone else gotten this type of message?  Just got an ipad and realized our itunes is not working.  I think when the most recent version was being installed, it got interrupted.
    Thanks

    I am getting an error writing to file: C:\Program Files\iTunes\iTunes Resouirces\pl.lproj\AppletVStream.nib\objects.xib. Verify that you have Access to that directory.
    That one's consistent with disk/file damage. The first thing I'd try with that is running a disk check (chkdsk) over your C drive.
    XP instructions in the following document: How to perform disk error checking in Windows XP
    Vista instructions in the following document: Check your hard disk for errors
    Windows 7 instructions in the following document: How to use CHKDSK (Check Disk)
    Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors, or use chkdsk /r (depending on which way you decide to go about doing this). You'll almost certainly have to schedule the chkdsk to run on startup. The scan should take quite a while ... if it quits after a few minutes or seconds, something's interfering with the scan.
    Does the chkdsk find/repair any damage? If so, can you get an install to go through properly afterwards?

  • File adapter Need to wait When Other Applicatio is writing the file

    Hi All,
    This is File to File Interface, iam using NFS here.
    While other application is writing the file to the Folder, XI Sender File Adapter shld wait for certain time and then pick it up.
    We have the Option " MSecs to Wait Before Modification Check" on File Sender Advanced TAB.
    But it is no Use, it is not behaving correctly.
    Please assist me on this
    Regards

    Hey Vamsi,
    I think you're good to go here. The behaviour is exactly as it should be. The polling interval takes priority when there is no file there but when there is a file there the modification check will take priority over polling interval so it will still wait the mandatory 2 minutes to ensure that no modification is taking place & that's exactly what you want. You don't want to pick up an incomplete file irrespective of when it was put there. So there will always be just over a 2 minute delay (or whatever you set the Msecs value to + a few seconds depending on where the polling cycle is when a file is written out but a max of 2 minutes & 19 seconds delay) when there is a file there but at least you'll have consistent data. If there is no file there the adapter will just poll every 20 seconds until a file arrives.
    The 2 minute 'wait' step is exactly that. The adapter will see the file then wait 2 minutes & probably does a timestamp comparison or something. It doesn't do a modification check within those 2 minutes. Having said that, I don't see why you can't reduce the Msecs interval. My reasoning is that you basically want to establish whether it's still being wriiten out before you pick it up. Even if you set it to 5 seconds you should still be able to pickup whether the file is being modified (I'm assuming that the check is doing a timestamp comparison). That will significantly reduce your time wait period.
    My assumption on the timestamp comparison was wrong It's actually does a comparison on file size when it reads the data in, see SAP Note (Point 3): [http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes/sdn_oss_bc_xi/~form/handler%7b5f4150503d3030323030363832353030303030303031393732265f4556454e543d444953504c4159265f4e4e554d3d383231323637%7d]
    Another suggestion made on the note: Get the writing application to write the file out with an extension different to the one you're polling for. Then, after they have completed writing out the file, they can do a re-name to the extension that you're polling for. That could also speed up things.
    Regards, Trevor
    Edited by: Trevor Naidoo on Oct 8, 2009 9:38 AM

  • Writing html file in a jeditorpane

    I have read one of your threads titled as "How to insert a string in a JEditorPane (Urgent)". according to this thread I am using insertString() method to write in an jeditorpane. what I am writing is an html file. when I used insertString() method it doesn't show the html content in my jeditotpane. it displays the source code of my html file. I have setContentType("text/html"); moreover I used setText() and it shows the html file correctly but it over writes the previous content of jeditorpane. please help me to be able to
    write to a jeditorpane without overwriting and displaying html file properly not its source code.
    following is my code:
             fr = new FileReader("myfile.html");
         BufferedReader br = new BufferedReader(fr);
         while ((lineread = br.readLine()) != null)
              find.append(lineread);
                       do{
                             last = find.lastIndexOf("str");
                          Integer index = myJEditorPane.getSelectionEnd();
                   String temp = index.toString();     
                   start=find.indexOf(temp, end);
                   end=find.indexOf("str", start);
                            Document doc = mynewContentPane.getDocument();
                   try{
                        doc.insertString(doc.getLength(),find.substring(start, end),null);
                   catch(BadLocationException exc){
                        exc.printStackTrace();
                   }Edited by: nasi on May 7, 2010 8:59 PM
    Edited by: nasi on May 8, 2010 12:09 AM
    Edited by: nasi on May 8, 2010 1:37 AM

    Welcome to the Sun forums.
    Subject: writing html file in a jeditorpane
    If you mean a JEditorPane then please use the correct case, so we can be confident you refer to the J2SE class, as opposed to a 3rd party jeditorpane that we neither know, nor support.
    nasi wrote:
    I have read one of your threads titled as "How to insert a string in a JEditorPane (Urgent)". ..I guess you mean [How to insert a string in a JEditorPane (Urgent)|http://forums.sun.com/thread.jspa?threadID=282569] from 2002. A lot has changed since 2002, but I suspect the basic way of appending text to a Document has not.
    BTW - Good to see you arrive with some Google-foo. ;-)
    ..according to this thread I am using insertString() method to write in an jeditorpane. what I am writing is an html file. when I used insertString() method it doesn't show the html content in my jeditotpane. it displays the source code of my html file. I have setContentType("text/html"); moreover I used setText() and it shows the html file correctly but it over writes the previous content of jeditorpane. I've not played much with changing existing documents, but try this source (adapted from code nabbed from the thread you mentioned).
    import javax.swing.text.*;
    import javax.swing.*;
    public class InsertStringTest {
        public static void main(String[] args){
            Runnable r = new Runnable() {
                public void run() {
                    //set GUI
                    JFrame f = new JFrame();
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    JEditorPane editorPane = new JEditorPane();
                    editorPane.setContentType("text/html");
                    editorPane.setText("<html><body><h1>Test!</h1><p>");
                    f.getContentPane().add(new JScrollPane(editorPane));
                    String testStr = "This is a test string. " +
                        "This is a test string. This is a test string. \n";
                    f.pack();
                    f.setSize(400,300);
                    f.setVisible(true);
                    //test with insertString()
                    long diff;
                    long startTime = System.currentTimeMillis();
                    Document doc = editorPane.getDocument();
                    for(int i=0; i < 500; i++){
                        try{
                            doc.insertString(doc.getLength(),testStr,null);
                        catch(BadLocationException exc){
                            exc.printStackTrace();
                    diff = System.currentTimeMillis() - startTime;
                    System.out.println("Time spent with doc.insertString() : " + diff);
                    editorPane.setCaretPosition(0);
            SwingUtilities.invokeLater(r);
    }

  • Help please! error writing to file cannot download itunes...cant fix!

    i really dont know what to do... i just got my computer a couple of months and something must have happened when i downloaded it the first time. i few times after using is i was having problems it said something about a corrupt file. So logically i thought to uninstall and then reinstal. but since then i have been dealing with this problem for a couple of weeks.
    installation will go well for a while (a couple of minutes) then i will this error.
    Error writing to file: C:\programfiles\commonfiles\apple\mobiledevicesupport\bin\AOSutils.dll
    then its says please verify that you have access to that directory.
    i have tried so many things and really dont know what to do. this cannot be manually deleted either.
    any advice would be appreciated!

    "Error writing to file: C:\Program Files\Common Files\Apple\Mobile Device Support\AppleMobileDeviceHelper.exe. Verify that you have access to that directory."
    Most commonly, it's caused by disk or file damage, J.
    Let's first try running a chkdsk over your C drive. There's Windows 7 instructions in the following document. Select both "automatically fix file system errors" and "scan for and attempt recovery of bad sectors" or use chkdsk /r (depending on which way you choose to go about things). You should be prompted to schedule the scan to run on restart. That sort of scan of the C drive should take a long time ... if it quits after a few minutes or seconds, something's interfering with the scan:
    [How to use CHKDSK (Check Disk)|http://www.w7forums.com/use-chkdsk-check-disk-t448.html]
    Does the chkdsk find/repair any damage? If so, try another iTunes install. Does it go through properly this time?

  • Can't install itunes. error  writing to file program files (x86)\Adobe\gnsk_dsp.dll

    I can't update itunes.
    During installation it says:
    Error while writing in file: Program Files (x68)\Adobe\gnsk_dsp.dll.
    Check whether you have the right to open that file.
    How can I remove this error?

    That one's consistent with disk/file damage. The first thing I'd try with that is running a disk check (chkdsk) over your C drive.
    XP instructions in the following document: How to perform disk error checking in Windows XP
    Vista instructions in the following document: Check your hard disk for errors
    Windows 7 instructions in the following document: How to use CHKDSK (Check Disk)
    Select both Automatically fix file system errors and Scan for and attempt recovery of bad sectors, or use chkdsk /r (depending on which way you decide to go about doing this). You'll almost certainly have to schedule the chkdsk to run on startup. The scan should take quite a while ... if it quits after a few minutes or seconds, something's interfering with the scan.
    Does the chkdsk find/repair any damage? If so, can you get an install to go through properly afterwards?

  • Error writing to file c:\config.Msi\5159655.rbf - 8596

    For a while now I have seen the same message about not being able to import or burn CDs because itunes was not installed properly, which didn't really bother me because I rarely did either of those. Then I was prompted to update itunes as usually happens when there is an update available, but along the way during the usuall update process, I recieved an error message:
         error writing to file c:\config.Msi\5159655.rbf
    So I said screw it, cancelled the update, and continued to put up with the burn/import notice every time I opened itunes. Eventually I just wanted to fix the problem for good so I completely uninstalled every itunes and apple related application I had on my computer; itunes, bonjour, quicktime, apple update thingy, apple mobile device support, apple application support, safari, etc. everything.
    I then proceeded to download and install itunes from online all over again, and much to my discouragement, itunes continued to open with the improper installation: unable to import or burn CDs notice every time.
    I don't know what else to do if completely uninstalling and reinstalling the program doesn't solve the problem.
    Help would be much appreciated

    I had this exact same problem just now, trying to upgrade to 10.7.
    I even got that error msg when trying to UNINSTALL iTunes!
    After hours of frustration trying everyone's different suggestions, I downloaded Revo Uninstaller http://www.cnet.com.au/apps/revo-uninstaller-10610875/ which solved the problem.
    Use it to help uninstall iTunes and related software components in the following order and then restart your computer:
    1. iTunes
    2. QuickTime
    3. Apple Software Update
    4. Apple Mobile Device Support
    5. Bonjour
    6. Apple Application Support (iTunes 9 or later)
    Then you can install iTunes from scratch.
    Good luck

Maybe you are looking for

  • My Macbook Late 2008 Fan Running All The Time

    Guys my macbook fan keep on running all the time is there any problem with the system? With this im attached my report, please anyone help me. Love u Guys for a big help! Hardware Information:           MacBook (13-inch, Aluminum, Late 2008)         

  • Cannot copy and paste objects in my project... Captivate 6

    Hello, I actually wrote about this yesterday, but I would like to mention it again because it's a big problem.  I have a Adobe Captivate 6 project, and I cannot copy and paste text captions, buttons, smart shapes, etc.  Do any of the experts out ther

  • I have 5g ipod touch And update for ios 7 won't come only 6.1.3???? Wat to do???

    Even when i try to update it to ios6.1.3 it says i am not connected to the internet when i am connected Please help...

  • Word document does not open in Pages

    It was my understanding that Pages is supposed to be able to open Microsoft Word documents. When my PC friends send me Word documents, they appear as "winmail.dat" in Mail and I cannot open them with either Pages or the Mac version of Microsoft Word.

  • Do all namespaces have to live in the 'DFSRoots' folder?

    Running through DFSN PS commands for the 70-411... My question is, do all DFS namespaces have to have their root shared folder in the 'DFSRoots' folder? Working through the 70-411 Exam Ref handbook, and entering.. New-DfsnRoot -TargetPath \\trey-dc-0