Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Write File Extensions to A text File.  RSS feed

 
Ranch Hand
Posts: 155
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys I am trying to store the Extensions of All the Files in A directory to a text File. Apparently only One extension is getting Written to the file. Where Could I be Missing Out in the Code. I would Also Appreciate if the Code was Able to read Extensions From Sub-Directories too. Here Is the Code I am using :
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're creating a new FileWriter each time you go round the loop. Which means you keep overwriting the same file. I'm a little surprised you're not hitting problems because they aren't being closed before another one comes along and writes over the top. But anyway....you need to create one Writer at the beginning and write all the extensions to that. (and then close it).
 
Stanley Mungai
Ranch Hand
Posts: 155
Java Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh Thank you Matthew That Worked Like Magic. But I did not close the BufferedWriter. When I close it it is Bringing Problems. Thank you sir for the Help.
 
Bartender
Posts: 1558
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stanley Mungai wrote:Oh Thank you Matthew That Worked Like Magic. But I did not close the BufferedWriter. When I close it it is Bringing Problems. Thank you sir for the Help.


What problem it is bringing? I assume you are closing BufferedWriter outside the loop (only once).

Also, even better approach would be : Iterate over the list, take all extensions and make a StringBuilder of it. Then dump it in the file at once (instead of writing each record one by one).

I hope this helps.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!