?
Solved

Problem Accessing a file in Java

Posted on 2004-11-30
33
Medium Priority
?
231 Views
Last Modified: 2010-03-31
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?

0
Comment
Question by:PeterMcDonnell
  • 8
  • 7
  • 7
  • +5
33 Comments
 
LVL 13

Expert Comment

by:petmagdy
ID: 12705570
not sure but try add after:
>>                 f_output.close();

 f_file.close(0;
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12705834
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12705846
>> f_file=null;

should be

 f_file=new File(myfilename);
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12705883
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
 
LVL 86

Accepted Solution

by:
CEHJ earned 50 total points
ID: 12705997
Make sure you don't have another program with the file open
0
 

Author Comment

by:PeterMcDonnell
ID: 12705998
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
 

Author Comment

by:PeterMcDonnell
ID: 12706023
The file is not open anywhere else (I can delete it from the command prompt)
0
 
LVL 14

Assisted Solution

by:sudhakar_koundinya
sudhakar_koundinya earned 100 total points
ID: 12706072
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
 

Author Comment

by:PeterMcDonnell
ID: 12706129
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12706247
Try to pass the filename something like this


c:/adobe/fonts/FontList.txt
0
 

Author Comment

by:PeterMcDonnell
ID: 12706268
I do pass a fully qualified path as my system.out statement is where this information is received from

0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12706295
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
 
LVL 37

Expert Comment

by:zzynx
ID: 12706326
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
 
LVL 3

Expert Comment

by:drjustin
ID: 12706459
0
 

Author Comment

by:PeterMcDonnell
ID: 12706518
have rebooted no luck
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12706563
is this problem coming from fontlist.txt or any other file that you are trying
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12707225
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
 

Author Comment

by:PeterMcDonnell
ID: 12707262
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12707740
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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12708142
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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12708173
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
 
LVL 17

Assisted Solution

by:krakatoa
krakatoa earned 100 total points
ID: 12708329
>> 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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12708387
> 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
 
LVL 17

Expert Comment

by:krakatoa
ID: 12708570
My point is the logic is wrong.
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12709337
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
 
LVL 17

Expert Comment

by:krakatoa
ID: 12709854
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
 
LVL 17

Expert Comment

by:krakatoa
ID: 12710017
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
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12711332
> 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
 
LVL 17

Expert Comment

by:krakatoa
ID: 12711476
>> 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
 

Author Comment

by:PeterMcDonnell
ID: 12716194
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12716286
8-)
0
 
LVL 3

Expert Comment

by:RMaruszewski
ID: 12716706
> 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
 
LVL 17

Expert Comment

by:krakatoa
ID: 12717977
>> Your system architect must be one clever guy, indeed.   ...

or perhaps just a little bit out of his mind.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month17 days, 6 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question