File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Input from console, writing to file Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Input from console, writing to file" Watch "Input from console, writing to file" New topic
Author

Input from console, writing to file

Geir Johnsen
Greenhorn

Joined: Dec 11, 2009
Posts: 2
Hi all!

I am trying to read input from the console, and write it to a file. I
The thought was that the user terminates the program by simply not typing any text, just hitting enter.. I was thinking a do-/while loop could do the trick..

Anyway, here's what I got so far:




This code gives me the error:

cannot find symbol
symbol : variable fromConsole
location: class TestJava2
while (fromConsole.lenth() > 0);



Any comments on this? I have no problem setting up writing one line at a time, but it is creating the loop that gives me the problem.
I would really appreciate any help.

Geir.
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
thats because you have declared the string variable fromconsole within the do loop which can not be seen outside do loop. So when your while loop condition uses fromconsole it cannot find that.


SCJP 1.6 96%
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32694
    
    4
Try this
Geir Johnsen
Greenhorn

Joined: Dec 11, 2009
Posts: 2
Thank you both for your reply

I got it working using the following code:



But can someone explain to me why the following line is needed:


If it is removed, nothing is written to the file..

Br
Geir
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32694
    
    4
the close() call ought to be in a finally block. It is there to make sure the Writer and the connection to the file are closed. Otherwise, that file may be inaccessible to other code.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Input from console, writing to file
 
Similar Threads
Writing to a file
I keep having a issue with variables and methods.
text formatting using java
Help with writing to a file!
Trouble with '.hasNext() '