Link to home
Create AccountLog in
Avatar of shampouya
shampouya

asked on

How do you use the Formatter class to create a text file?

I noticed that the program below creates a text file below in the folder that contains your java project. But why does the code below create a file? I see that the Formatter object is created and called x, but why does defining x create a file? I didn't realize that simply defining something could result in a tangible action.
import java.util.*;

public class apples {

    public static void main(String[] args) {

        final Formatter x;

        try{
            x = new Formatter("fred.txt");
            System.out.println("you created a file");
        }
        catch(Exception e){
            System.out.println("you got an error");
        }
        
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account

That's waht API writes:
fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
If you don't want to craete file you can create PrintStream as an argument of constructor
 and use ByteArrayOutputStream as argument for PrintsSteream creation.
After that you can write it all to a String, rather than to file
Avatar of shampouya
shampouya

ASKER

When you said "this type of constructor" in your first post, what did you mean? I didn't realize that defining an object is called a "constructor." I thought that a constructor was when you use a method with the same title as the class, and initialize variables in that method.
Or you can even use StringBuilder as an argument of Formatter  and then get string from that StringVBuilder - then you'll avoid
creating file - but with String as argument constructor cretaes the file

Look at this constructor:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#Formatter%28java.lang.Appendable%29

It would alloow to create Formatted with StringBuilde which implements Appandable
I don't want to change anything about the program, I just want to understand why a file was created, which I know understand, but I don't understand why you called this a "constructor":

x = new Formatter("fred.txt");
The constructor is indeed a method which which has the same name as the class; uausllay in this method you initialize instance variables
a little too much information for_yan :)
However you should not think that initializing variables is the only thing that can be done in constructor.
It wortks as any other method - and executes each line of its codwe - whatvere people who wrotye the
constructtor put there - that is what t will execute
People who wrote Formatter thought that it sis convenient to create file for output in constructor - so they did it.
And we cannot blem them becuase they documented it in the API. We just need to read the API and use those constructors which
have functionality which we want and not use those constructors which do something which we do not want them to do.
But why did you call this a constructor?? This isn't even a method.

x = new Formatter("fred.txt");
Shampouya, When you create a new instance of an object you are calling the constructor. Your code instantiates a new Formatter object using its one argument constructor that accepts the file name.

Is an important concept to understand.
Have a look at tutorial: Java: Constructors
It is a method - it accepts parameteres and executes code which makes up its body.
Constructors may be very sophisticated - they can do a lot of complex work inside their body - not just create objects.
for_yan, am i right in saying "the constructor returns the address of the object"? And the address is stored on the heap?
So when you said in your first post :

"This type of constrauctor of Formatter with one string as arguyment cretaes file"

You should have said this instead:

"The formatter class contains a constructor that creates a file when it takes one string as its argument"




The way you used the word "this" confused me.
Constructor is a method whose name coincided with the name of the class and which cannnot have a return statement.
And you invoe excution of this method using the "new" operator.
Other than that - constructor is a method which can do anything what any other normal method can do - read and wrote files,
do lengthy calculations, create viasual elements, etc.etc.
And in numerous constructors especially of your custom classes (which you create yourself - not from standard
library) you may have all those operation in constructor
No there is no contradiction between these two sentences.

A class can have different constructors - they all have the same name but they can have different
argument - different numbers of arguments and different types of arguments .
When I wrote "this type of constructor" I meant - the constructor of class Formatter which takes one paramter of type String
I'm not confused about constructors, I'm confused about why you called

x = new Formatter("fred.txt");

a constructor. x is only an object of a class that contains a constructor that is called when you create the object. It is not a constructor, it only calls the instructor. The wording is very important don't you think?
An this constructor - with one paramter of type String can be quite different form another constructor which takes
one paramtere of type StringBuilder
The compiler will determine by the number and type of arguments - which of the existng constructors
to execute - and the actual body of these constructores can bwe very different - one of them may create file
in the process of its execution, anothe can jsut initialize some fileds in memory - whatever the authors of the class wrote...
Ok, I agree with you on this, when you wrote "this type of constructor" you meant - the constructor of class Formatter which takes one paramter of type String.

I was very confused for a minute.

you cannot say "an object of a class that contains a constructor".
object cannot contain a constructor, object can be created by constructor

new Formatter("fred.txt") is a call to constaructor - true

this call creates instance of the class

this instance is assigned to variable x

 
Thanks for the help as always. A little more info than I wanted, but helpful. Thanks.
"isntance of the class" is a synonuym to the "object of particular the class"
I disagree with you, you can say "an object of a class that contains a constructor" because classes DO contain constructors. You can't disagree with me on that. Obviously I don't know as much Java as you but it's important that you don't disagree with the basic concepts that I DO know.
You are always welcome.

In EE it always happens to be alittle mor info as I not always know upfront what you don't understand.
It would be of course much easier when we would have been talking
Well, you probably can say so, but it is not common expression - you can say class has such and such constructor with such and such paramteres
- this is much more common than "contains" in this context.
Besides when  you write  "x is only an object of a class that contains a constructor" - it is ambiguos because it sounds as if "x contains constructor" -
so better not to use such phrase.
If you understand it correctly that "class has a constructor" not its instance, and instance can only be created by constructor - then it is fine.
But it is rather common thing that distinction between class and instance is blurred - and in fact in very many situations
this is a very important distinction, beacuse class is in fact abstract notion, whereas instance of the class is a real object sitting
in some part of physical  memory, etc,etc.