This site requires JavaScript, please enable it in your browser!
Greenfoot back

Report as inappropriate.

davmac
davmac presents ...

2012/5/15

filereader

This scenario is a demonstration of how to read the contents of a file in your scenario.

All the code is in the 'ReaderWorld' class. It's reasonably straightforward, though does need to use exception handling which is a more advanced topic.

Please note, this scenario doesn't do anything when you run it. When it starts, it reads the contents of the 'content/story.txt' file within the scenario, and displays the first five lines of text in that file.

8099 views / 1440 in the last 7 days

4 votes | 1 in the last 7 days

Tags: demo with-source

open in greenfoot
Your browser is ignoring the <APPLET> tag.
SPowerSPower

2012/6/5

Is it also possible to write to a txt file?
davmacdavmac

2012/6/5

That depends on what you mean. You can't write to files in a scenario that's uploaded here to greenfoot.org; you can with scenarios that you run within Greenfoot or export as an application. Please ask in the discussion forum if you want help with that.
SPowerSPower

2012/6/6

Ok, thanks for the info.
PHORNE31PHORNE31

2012/6/7

I'm still trying to read a file to appear in the world, but still having a difficult time in doing so. I stored the file in FileDen to read it from and that didn't work. I tried to read it from my labtop, and that didn't work either. I used the line InputStream input = getClass().getClassLoader().getResourceAsStream("filename.txt"); in both scenarios( with the import.java.io; statement in the beginning line). Is there anything else I should do?
SPowerSPower

2012/7/6

I've got a tip for you, davmac: you now set the image of a TextActor instance, but if you want to be a good object oriented programmer, the TextActor instances should know their images better than someone else. So it would be a better design if you would create a constructor int TextActor with an array of strings, and it creates its own image. This is just a tip, there's nothing wrong with the result right now: it would just be a better design.
davmacdavmac

2012/7/6

SPower, thankyou, but the code is how it is for a reason - I wanted all the important parts to be in one place (the ReaderWorld class). That's because this is intended as a simple demonstration / example - it's not meant to serve as the basis for anything else. And no offence, but I really don't need tips on Object Oriented design. I've been doing this a looooong time. ;-)
SPowerSPower

2012/7/6

Ok, that's a good reason. And I could have known your knowledge of object oriented designing experience, since you're one of the creators of greenfoot :)

Want to leave a comment? You must first log in.

Who likes this?

Philinö SPower mik