• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can't write to file  RSS feed

 
Peter Ariyibi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code below compiles ok but when i run it nothing happens - i want to be able to write whatever i type (system.in) to a file called fromkeyboard. Any thoughts on why this is would be appreciated
 
Lester Burnham
Rancher
Posts: 1337
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A little hint: Since nothing is assigned to "s", it is null before it reaches the while loop...
 
Peter Ariyibi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.. i have initialised s before the while loop and that seemed to have solved the problem. I then noticed that my out.close and in.close method calls were outside the try block which i have corrected. Although the code works (i can type gibberish and i assume it is written to file), when i check the fromkeyboard file it is empty! Any hints on why the keyboard input is not being written to file?
 
Paul Clapham
Sheriff
Posts: 22819
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code might be subject to exceptions. But you would never know, for two reasons:

  • Your catch block ignores them
  • You are using a PrintWriter, which ignores exceptions


  • You can fix the first problem like this:


    And you can fix the second problem by using a BufferedWriter rather than a PrintWriter.
     
    Jesper de Jong
    Java Cowboy
    Sheriff
    Posts: 16057
    88
    Android IntelliJ IDE Java Scala Spring
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Welcome to JavaRanch.

    Please UseCodeTags when you post source code, that makes the code much easier to read. Being a moderator, I added the code tags to your post above for you.
     
    Paul Clapham
    Sheriff
    Posts: 22819
    43
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Peter Ariyibi wrote:I then noticed that my out.close and in.close method calls were outside the try block which i have corrected.


    So now you are asking a question about code which we haven't seen yet...
     
    Joanne Neal
    Rancher
    Posts: 3742
    16
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Peter Ariyibi wrote:thanks.. i have initialised s before the while loop and that seemed to have solved the problem.


    Rather than initialising s to some random value before the loop, you will find that this sort of loop is often written like this
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!