Problem Accessing a file in Java

I have the following code

private static void WriteStringToFile(String myfilename,String myString,boolean Overwrite){
          File f_file=new File(myfilename);
          
          if (f_file.exists()==true){
                if(Overwrite==true){
                      
                      if (f_file.delete()==false){
                            System.out.println("Deleting File "+myfilename+" Failed");
                      }
                }
                
          }
          f_file=null;
          try{
                  FileOutputStream f_output=new FileOutputStream(f_file);
                  f_output.write(myString.getBytes());
                  f_output.close();
                  }
            catch (IOException e){
                  System.out.println("File IO Error Creating File "+myfilename+"\r\n"+e);
            }      
            
          
    }

if i call it once it works ( i am sending a true to the overwrite) if I call it and the file exists the delete fails.

i get:
(The requested operation cannot be performed on a file with a user-mapped section open)
 yet I have closed the stream.

I get the same problem if rem out the delete lines

not sure why

can anyone help?

PeterMcDonnellAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

petmagdyCommented:
not sure but try add after:
>>                 f_output.close();

 f_file.close(0;
0
sudhakar_koundinyaCommented:
private static void WriteStringToFile(String myfilename,String myString,boolean Overwrite){
         File f_file=new File(myfilename);
         
         if (f_file.exists()==true){
              if(Overwrite==true){
                   
                   if (f_file.delete()==false){
                        System.out.println("Deleting File "+myfilename+" Failed");
                   }
              }
             
         }        
        f_file=new File(myfilename);
         try{
                FileOutputStream f_output=new FileOutputStream(f_file);
                f_output.write(myString.getBytes());
                f_output.close();
                }
           catch (IOException e){
                System.out.println("File IO Error Creating File "+myfilename+"\r\n"+e);
           }    
           
         
    }
0
sudhakar_koundinyaCommented:
>> f_file=null;

should be

 f_file=new File(myfilename);
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

sudhakar_koundinyaCommented:
Simple thing you can dow with this code is if you don't want to overwrite, then here is the code

 private static void WriteStringToFile(String myfilename,String myString,boolean Overwrite){
         File f_file=new File(myfilename);
         
         if (f_file.exists()==true){
              if(Overwrite==true){
                   return;
                   }
              }
             
         }        
/** Your Other Code Here **/      
         
    }
0
CEHJCommented:
Make sure you don't have another program with the file open
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PeterMcDonnellAuthor Commented:
Fundamentally I need to delete the file (if it exists ) as the contents are different

I have tried

 f_file=new File(myfilename);

this does not work

also if I change:

FileOutputStream f_output=new FileOutputStream(f_file);

to

FileOutputStream f_output=new FileOutputStream(myfilename);

even though this then isolates the try code segment this also does not work

the failure appears to be due to an open stream but the stream is closed with the line

f_output.close();

it actually fails on the delete() statement as in it returns false






0
PeterMcDonnellAuthor Commented:
The file is not open anywhere else (I can delete it from the command prompt)
0
sudhakar_koundinyaCommented:
check this



File file=new File(myfilename);
FileOutputStream fout=null;
if(overwrite)
{
fout=  new FileOutputStream (file); //overwrites the contents
}
else
{
   new FileOutputStream (file,true);//appends the contents
}
0
PeterMcDonnellAuthor Commented:
this also fails with the same error

File IO Error Creating File c:\adobe\fonts\FontList.txt
java.io.FileNotFoundException: c:\adobe\fonts\FontList.txt (The requested operation cannot be performed on a file with a user-mapped section open)

0
sudhakar_koundinyaCommented:
Try to pass the filename something like this


c:/adobe/fonts/FontList.txt
0
PeterMcDonnellAuthor Commented:
I do pass a fully qualified path as my system.out statement is where this information is received from

0
sudhakar_koundinyaCommented:
try do following at command prompt and then try ur java example

attrib -h -r -s -a c:\adobe
attrib -h -r -s -a c:\adobe\fonts
0
zzynxSoftware engineerCommented:
Did you already try to reboot your machine and try again.
I know it sounds rather stupid, but it wouldn't be the first time this helps...
0
drjustinCommented:
0
PeterMcDonnellAuthor Commented:
have rebooted no luck
0
sudhakar_koundinyaCommented:
is this problem coming from fontlist.txt or any other file that you are trying
0
RMaruszewskiCommented:
Are you able to delete/rename this file from you OS level?
(by calling "del", or "rm", or pressing F8 in Windows Commander, etc.)
0
PeterMcDonnellAuthor Commented:
I can delete the file from the same prompt window as i run the java programme

i.e del c:\adobe\fonts\fontlist.txt

Works

Also I have the same problem on other directory and files

0
sudhakar_koundinyaCommented:
I wanted to know one more question from ur side. If u know c/c++

try this

#include "studio.h"

void main()
{
  FILE* fp=fopen("c:\\a.txt","w");
    if(fp==NULL)
    printf("Error in creation file");
}
0
RMaruszewskiCommented:
I've actually run this example - and it works perfectly on my system... 8-/
Here's the code of my method (just a little modified):

  private static void writeStringToFile(String myfilename, String myString, boolean overwrite)
  {
    File f_file = new File(myfilename);
         
    if (f_file.exists())
    {
      if (!overwrite)
        return;
     
      if (!f_file.delete())
        System.out.println("Deleting File "+myfilename+" Failed");
    }

    try
    {
      FileOutputStream f_output=new FileOutputStream(f_file);
      f_output.write(myString.getBytes());
      f_output.close();
    }
    catch (IOException e)
    {
      System.out.println("File IO Error Creating File "+myfilename+"\r\n"+e);
    }    
  }
0
RMaruszewskiCommented:
I called it like this:

    writeStringToFile("myfile.txt", "myString1", true);
    writeStringToFile("myfile.txt", "myString2", true);
    writeStringToFile("myfile.txt", "myString3", false);

...and "myfile.txt" contains string "myString2" (as it supposed to be).
0
krakatoaCommented:
>> File f_file=new File(myfilename);
       
         if (f_file.exists()==true){
<<

What is the sense in creating a new file object then testing for its existence may I ask?
0
RMaruszewskiCommented:
> What is the sense in creating a new file object then testing for its existence may I ask?

The File constructor doesn't create file "physically".
The actual file is created when you call FileOutputStream constructor.
0
krakatoaCommented:
My point is the logic is wrong.
0
RMaruszewskiCommented:
Oh yeah. You're right. It doesn't make much sense.

Unless it was to be used as the "append to file" indicator...
But in this case this method should look like this:

  private static void writeStringToFile(String myfilename, String myString, boolean append)
  {
    try
    {
      FileOutputStream f_output=new FileOutputStream(new File(myfilename), append);
      f_output.write(myString.getBytes());
      f_output.close();
    }
    catch (IOException e)
    {
      System.out.println("File IO Error Creating File "+myfilename+"\r\n"+e);
    }
  }
0
krakatoaCommented:
Not sure why you put "append" there when he wants to overwrite it, or not write at all.

.
.
.

sm = System.getSecurityManager();
.
.
.


private static void writeStringToFile2(String myfilename, String myString, boolean overwrite)
 {

      if (!overwrite){return;}

      try{try{

            sm.checkRead(myfilename);

          }catch(NullPointerException npe){}

       }catch(SecurityException secrtyexcep){return;}


           File f_file = new File(myfilename);

   try

   {
     FileOutputStream f_output=new FileOutputStream(f_file);
     f_output.write(myString.getBytes());
     f_output.close();
   }
   catch (IOException e)
   {
     System.out.println("File IO Error Creating File "+myfilename+"\r\n"+e);
   }    
  }
0
krakatoaCommented:
And I should have mentioned, for clarity, that if you want to overwrite at all, then you won't need to explicitly delete the file - which is much the same principle as why the method should return if 'overwrite' is false. Perhaps the method should not be called if overwrite is false, since you dont need a file at all in that case. ;)
0
RMaruszewskiCommented:
> Not sure why you put "append" there when he wants to overwrite it, or not write at all.

Because I thought you meant it. :-]
And I still think there's a flaw in design - but on a higher level. Look, why would you design a method which would allow you to write something to file, but do it only if this file doesn't exist? And, assuming that you'd even need something like this, why would you want to pass the "overwrite" parameter to it? The caller of this method should be well aware if this method was already called or not, and it should hold this information as its private variable. If somebody would call this method with "overwrite" parameter set to "false", it would mean that he doesn't know what (wnd why) he's really doing.

PS. And, of course, you're absolutely right about this file checking & deletion.
0
krakatoaCommented:
>> Because I thought you meant it. :-]

Not quite sure what you are getting at there; but anyway, sometimes people ask questions which are not presented in context. The asker wants to write stuff to a file, and if he wants the unnecessary luxury of handling an overwrite argument then that's up to him I suppose - who knows? My code is only trying to fake a different way of establishing if the file already exists or not (which is again a redundant activity), and I wanted to get away from using new File() and then testing for it as I said. The SecurityManager and its NPE on the filename, kludges its way around that. ;) I'm not saying it's the best, or even a good, way. ;)
0
PeterMcDonnellAuthor Commented:
The File in question is a summary file which only needs to be overwritten in certain circumstances (when a time or a specific change has occured) the routine needs to write a new text file and overwrite the old one when necessary. The purpose is to isolate this process in one routine for future use. The overwrite parameter also makes it compatable with calling file structure for other file routines (in accordance with a specification).

In conclusion given all the advice the problem must be on the machine and any related code.

Thanks to all
0
CEHJCommented:
8-)
0
RMaruszewskiCommented:
> The overwrite parameter also makes it compatable with calling file structure for other file routines (in accordance with a specification).

I see. That's very pragmatic solution...
Your system architect must be one clever guy, indeed.
0
krakatoaCommented:
>> Your system architect must be one clever guy, indeed.   ...

or perhaps just a little bit out of his mind.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.