Solved

How do I...

Posted on 2000-05-16
10
149 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
ID: 2814816
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
ID: 2814868
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
ID: 2814932
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
ID: 2815023
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
ID: 2815050
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:rmmarsh
ID: 2815165
see comments above...
0
 
LVL 3

Accepted Solution

by:
falter earned 100 total points
ID: 2815286
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
ID: 2816842
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
ID: 2817516
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
ID: 2818058
thanks, absolutely clear now...
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 68
recursion example 16 111
java 8 lambda expresssions exception handling 3 75
eclipse shortcuts 9 45
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.

895 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