Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Writing to a file

 
Justine Hume
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I would like the selection that the user makes to be written to a .txt file, but am unsure how to do this. Can anyone help?

Thanks
 
Campbell Ritchie
Sheriff
Pie
Posts: 50196
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
just read a thread where I made similar suggestions about text files for somebody else. Try this post and the links therein.
 
Mike Zal
Ranch Hand
Posts: 144
Fedora Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
File IO with BufferedOutputStream example
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are tons of examples of this on the internet, but first you should read Sun's tutorial on Reading and Writing to files: http://download.oracle.com/javase/tutorial/essential/io/file.html Then if you have questions after that posted what you tried.

Hunter
 
Justine Hume
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry guys, I'm kind of new to Java and I have had a look at the links and have no idea how to implement that code with mine
 
Mike Zal
Ranch Hand
Posts: 144
Fedora Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Justine Hume wrote:Sorry guys, I'm kind of new to Java and I have had a look at the links and have no idea how to implement that code with mine


Step 1) Create some type of FileWriter (You need to specify the file location)
Step 2) wrap it with a BufferFileWriter (Usually done on the same line as step 1)
Step 3) Replace a System.out.println() with <your writer>.write() call
Step 4) <your writer>.close()

You should have new file in the location specified in Step 1.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50196
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike Zal wrote: . . .
Step 2) wrap it with a BufferFileWriter (Usually done on the same line as step 1)
Step 3) Replace a System.out.println() with <your writer>.write() call
Step 4) <your writer>.close() . . .
careful about spellings; it's a BufferedWriter. And writeLine(), surely?

You will also have to wrap the whole thing in a try-finally-catch. Look here, and Rob's reply. Then you substitute the Readers with Writers, and check the API where there is an underlined class name above, to check I have the method names right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic