Solved

How do I...

Posted on 2000-05-16
10
148 Views
Last Modified: 2012-05-04
I have written the following method...

public void writeFile(String loggingData) throws java.io.IOException {
   BufferedWriter out;      
   File outfile;

   outfile = new File("e:","abc.test");  //  this is where I want the log to go...
   out = new BufferedWriter(new FileWriter(outfile));
   out.write(loggingData,0,44);
   out.flush();
   out.close();      
}


My question is how do I determine if the file already exists ('cause I want to append to the file, as in logging)... I don't see how I can use the File.exists()  method on an object that doesn't exist yet... I was thinking of using an 'if' statement, but then when I put the file declarations in the block, the compiler tells me that 'out' is not defined.
0
Comment
Question by:rmmarsh
10 Comments
 
LVL 1

Expert Comment

by:ranak
Comment Utility
use FileOutputStream which has the option to append to file

FileOutputStream fs=null;
                    try
                    {
                    fs = new FileOutputStream(fileName,true);
                    }
                    catch(IOException ioEx)
                    {
                    fs =  new FileOutputStream(fileName);
                    }
                    DataOutputStream dataLogFileName = new DataOutputStream(fs);
0
 

Author Comment

by:rmmarsh
Comment Utility
Does this method 'open' and 'close' (resulting in much overhead) each time?  I want to be able to create the object, have it persist until I explicitly close it, all the while being able to write to the file.
0
 
LVL 1

Expert Comment

by:karthicraja
Comment Utility
a) in Log evertime you have to open and close because it is used to trace the Crash or abnormal termination. writing then and there will avoid buffering of the content.

b)Log may have to be a Singleton class so, instantiate as a static variable in the main class and use it, so that garbage collection will not occur unnecessarily.

This function will help you to append.

public void log(String _error) throws IOException
{
private BufferedWriter write;
boolean append = true;
write = new BufferedWriter(new FileWriter(fileName, append));
              write.write(_error,0,_error.length());  
              write.newLine();                    write.close();
}

hope this helps.
karthic
0
 

Author Comment

by:rmmarsh
Comment Utility
this is basically what I had... also, I don't know what a  "Singleton" class is, so I really don't understand what you are talking about with regard to it... what I want to do is have a logging function which writes data to a file.  I do NOT want to create the object/open the file each time I want to do a write... I want to open the file (create the object) ONCE, write many different times, and finally CLOSE the file.  I am concerned about the overhead... I tried putting the code which creates the objects in an "if" block, but then I couldn't reference the file that I wanted to write to (why it was unreachable, I don't know)... is there a way to do this (like one used to do in C/C++)?
0
 

Author Comment

by:rmmarsh
Comment Utility
this is basically what I had... also, I don't know what a  "Singleton" class is, so I really don't understand what you are talking about with regard to it... what I want to do is have a logging function which writes data to a file.  I do NOT want to create the object/open the file each time I want to do a write... I want to open the file (create the object) ONCE, write many different times, and finally CLOSE the file.  I am concerned about the overhead... I tried putting the code which creates the objects in an "if" block, but then I couldn't reference the file that I wanted to write to (why it was unreachable, I don't know)... is there a way to do this (like one used to do in C/C++)?
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:rmmarsh
Comment Utility
see comments above...
0
 
LVL 3

Accepted Solution

by:
falter earned 100 total points
Comment Utility
First after constructing outfile = new File()
you can test existance with
outfile.exists() returning a boolean.
So you can construct your FileWriter with:
 out = new BufferedWriter(new FileWriter(outfile.getAbsolutePath(),outfile.exists()));
This will give you a FileWriter which appends if the file already exists.

Second:
Single instance is means not to have a public constructor for your log class.
something like that

public class MyLog {
  static Mylog instance = null;
  private Mylog(){
      ...
        //create LogFile and so on
      instance = this;
  }
public static MyLog getInstance()
{
  if (instance == null)
  {
    return new MyLog();
  }
  else
  {
    return instance;
  }
}
public void synchronized write(String s) throws (...)
{
  // do something
}

use synchronized in write if you will access your Log in a multithreaded application.
 
}

So you can call the write method every where with
Mylog.getInstance().write(...);
or
MyLog log = MyLog.getInstance();
log.write(...);

The private comnstructor and the static getInstance method garants that only one
object of this class will be instantiated in one JVM.

At least it means write a separate class for your logging handling all the stuff and implementing singleinstance design pattern..
0
 

Author Comment

by:rmmarsh
Comment Utility
Thank you... I still don't understand how you can test for something that "exists()" after you create the object.  Doesn't the creation of the object imply that the file exists?
0
 
LVL 3

Expert Comment

by:falter
Comment Utility
rmmarsh ,

No!!!
exists() will not test the existance of the created File object, it will test if by your File Object described object exists in your case the physical File.

You didn't create anything with
File myFile = new File("myFile.txt");
on your harddisk just a Java Object describing a file in your filesystem and knowing how to get some Information about this file.

If you open a FileWriter than something will happen on your harddisk.

Or look at the Javadoc of java.io.File
Instance of this class represents a filename of a file or directory on the host file system .... (extract from Javadoc JDK1.1.7)
0
 

Author Comment

by:rmmarsh
Comment Utility
thanks, absolutely clear now...
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

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…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
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…

771 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now