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

Java

Avatar of undefined
Last Comment
for_yan

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
for_yan

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
for_yan


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.
for_yan

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
ASKER
shampouya

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.
Your help has saved me hundreds of hours of internet surfing.
fblack61
for_yan

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
for_yan


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
ASKER
shampouya

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");
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
for_yan

The constructor is indeed a method which which has the same name as the class; uausllay in this method you initialize instance variables
ASKER
shampouya

a little too much information for_yan :)
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
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
for_yan

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.
ASKER
shampouya

But why did you call this a constructor?? This isn't even a method.

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

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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Gregg

Have a look at tutorial: Java: Constructors
for_yan

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.
Gregg

for_yan, am i right in saying "the constructor returns the address of the object"? And the address is stored on the heap?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER
shampouya

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.
for_yan

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
for_yan

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
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
shampouya

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?
for_yan

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...
ASKER
shampouya

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.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
for_yan


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

 
ASKER
shampouya

Thanks for the help as always. A little more info than I wanted, but helpful. Thanks.
for_yan

"isntance of the class" is a synonuym to the "object of particular the class"
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
shampouya

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.
for_yan

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
for_yan

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.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck