-4

I have made a textual minesweeper game (here you can find the program). I want to initialize some data by the help of a file. The file should be readable for humans and easy to modify with a simple text editor. The file should look for example like this and it should allow comments:

# columns and rows
size:10
# describes how the field is selected
# 1 - <o x x> (for example e 5 7 which means explore field with coordinates 5 7)
# 2 - easy entering format
format: 1 
# possibility that a field is bombed (1 / possibility)
possibility: 8

In which part of the program and in which manner should I read such a file? What is the most efficient way to read such a file? Thank you for all answers!

4

2 Answers 2

6

Raw Java world uses Java propeties format to handle similar configuration tasks. Dedicated class Properties makes this trivial.

 try(Reader reader = Files.newBufferedReader(Path.get("config.properties"), StandardCharsets.UTF_8)) {
     Properties properties = new Properties();
     properties.load(reader);
     int size = Integer.valueOf(properties.getProperty("size"));
     int format = Integer.valueOf(properties.getProperty("format"));
     .....
 }
3
  • I agree. Why reinvent the wheel?
    – Neil
    Feb 28, 2018 at 13:06
  • 1
    If you dont like properties there is still yaml, json, xml ... all of which wont re-invent wheels though some might need external libraries.
    – Newtopian
    Feb 28, 2018 at 14:35
  • XML, YAML, JSON model tree structures, while OP requests a key-value storage, which is a simpler subset.
    – Basilevs
    Feb 28, 2018 at 15:48
1

if you use Java (and you do), work with Spring. it makes your life so much easier in such cases!

and specifically in this case, you just use something like

<context:property-placeholder 
    ignore-resource-not-found="true" 
    location="classpath:default.properties" />

and you have all the properties ready for use (it reads everything upon startup)

1
  • 5
    For the OP's needs, Spring is like using a cannon on a squirrel. Heavy to lift, hard to aim, and leaves a mess behind. Feb 28, 2018 at 13:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.