Solved

How do I...

Posted on 2000-05-16
10
151 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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
 

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
print map entry 34 72
hibernate example issues from command prompt 10 50
Android development question 2 54
running on tomcat not jboss eap 7.0 3 18
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

837 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