Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Assigning string to variable type File.  RSS feed

 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
Look at the code below.

Variable "file" is instance of type "File".

How could I able to assign string output to variable "file".
with no exception. ?
ie. file = file.getAbsoluteFile();

thanks
siva


 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Siva,

I'm not sure exactly what you're trying to do or why, but consider this:

You can simplify that to:

Does that help? Maybe you'd find the I/O section of Sun's Java Tutorial interesting.

Jules
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To answer your question as I literally understand it, "You can't."

A "String" object is not a "File" object. Since "file" is a reference of type "File," it can only be used to refer to objects of type "File."
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or, for bonus fun, you could simplify it to

 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Siva kandasamy:
How could I able to assign string output to variable "file".
with no exception. ?
ie. file = file.getAbsoluteFile();


getAbsoluteFile() has File as return type, not String. That's why it is working.

The conversion to a string is happening in the println method. Take a look at the source of PrintStream.println(Object) (the source is coming with the JDK, in a zip or jar file). You will see that

System.out.println(file);

is equivalent to

System.out.println(String.valueOf(file));

which will print "null" if file is null, file.toString() otherwise.

Did that help?
 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Thanks every one.

Ilja,
Thanks for answering me. Exactly.

-siva
[ September 07, 2004: Message edited by: Siva kandasamy ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!