Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (109)
games submitted by our members
Games in WIP (536)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  File reading for save function  (Read 754 times)
0 Members and 1 Guest are viewing this topic.
Offline kingroka123

JGO Knight


Medals: 27
Projects: 5
Exp: 1 year


Gamer's Helmet


« Posted 2013-06-24 19:28:56 »

I need to figure out how to differentiate between integers in my save file:
1  
2  
3  
4  
5  
6  
0,595,1
0,611,0
0,627,2
0,643,2
0,659,2
0,675,2

I want this to translate to:
1  
x,y,blockType

each line of numbers represent a new block to be spawn when this file is called. I just need to figure out how to tell which number goes for which variable. The x,y,and blocktype are all stored in arraylists and can already be used to spawn blocks.

here is my reading files code so far:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
public static void ReadFile(String path){
           try {
               FileInputStream fStream = new FileInputStream(path);
               BufferedReader in = new BufferedReader(new InputStreamReader(fStream));
               while (in.ready()) {
                   System.out.println(in.readLine());
               }
               in.close();
           } catch (IOException e) {
               System.out.println("File input error");
           }
       }

 thanks for your help

Offline Z-Man
« Reply #1 - Posted 2013-06-24 20:06:31 »

I'd just ignore the possibility that the line is formatted incorrectly. Then simply throw the line into a StringTokenizer and get the 3 ints you need.
1  
2  
3  
4  
5  
StringTokenizer tokenizer = new StringTokenizer(line, ",");
if(tokenizer.countTokens() >= 3) {
   list1.add(Interger.valueOf(tokenizer.nextToken());
   // etc, etc.
}


You could also take the approach of ensuring that each int is what you want, then just parsing out the ints. This is, in my opinion, a waste as you're unlikely to want to edit large maps by hand.
1  
2  
// Text file
x=0 y=595 id=1


Or, if you want to save space on map sizes you could just read/write integers to the file in sets of three. First three integers are a block and so on.
Offline GabrielBailey74
« Reply #2 - Posted 2013-06-24 20:21:18 »

Just wrote this up hope it's what you're looking for ^_^
(Documented so you know what's occurring ^_^)

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
   LinkedList<Block> blocks = new LinkedList<Block>();

   public void loadChunk(String path2File) throws FileNotFoundException {
      FileReader fr = new FileReader(new File(path2File));
      BufferedReader br = new BufferedReader(fr);

      // the line being read
     String line = "";

      try {
         while ((line = br.readLine()) != null) {

            // line will be read as: 0,595,1

            // turn the line into 3 strings
           // each letter seperated by a comma

            String[] dataArray = line.split(",");

            // dataArray[0] = 0; (X)
           // dataArray[1] = 595; (Y)
           // dataArray[2] = 1; (BlockType)

            // CASTING FROM STRING TO INTEGER
           int x = Integer.parseInt(dataArray[0]);
            int y = Integer.parseInt(dataArray[1]);
            int blockType = Integer.parseInt(dataArray[2]);

            // add the block to the block list & load another
           blocks.add(new Block(x, y, blockType));
         }
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         try {
            br.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline kutucuk

Senior Member


Medals: 5
Exp: 3 years



« Reply #3 - Posted 2013-06-24 20:37:56 »

What you are looking for is; regular expressions: http://docs.oracle.com/javase/tutorial/essential/regex/
Offline kingroka123

JGO Knight


Medals: 27
Projects: 5
Exp: 1 year


Gamer's Helmet


« Reply #4 - Posted 2013-06-24 20:55:01 »

I'm getting this error:
1  
2  
3  
4  
5  
6  
Exception in thread "Thread-3" java.lang.OutOfMemoryError: Java heap space
   at sqr.gui.org.MainMenu.LoadGame(MainMenu.java:56)
   at sqr.main.org.BlockSpawn.<init>(BlockSpawn.java:95)
   at sqr.main.org.Game.render(Game.java:236)
   at sqr.main.org.Game.run(Game.java:161)
   at java.lang.Thread.run(Unknown Source)


Is this because i'm trying to load too much it is about 450 blocks

Offline GabrielBailey74
« Reply #5 - Posted 2013-06-24 21:25:34 »

Is this because i'm trying to load too much it is about 450 blocks

Could you post line # 56 in MainMenu.Java?
1  
at sqr.gui.org.MainMenu.LoadGame(MainMenu.java:56)


Would be better if you could post the whole "Load Game" method ^_^

Offline kingroka123

JGO Knight


Medals: 27
Projects: 5
Exp: 1 year


Gamer's Helmet


« Reply #6 - Posted 2013-06-24 21:28:14 »

Never mind i fixed it thanks for the help guys
 Grin

Offline nhydock

Junior Member


Medals: 4
Projects: 2



« Reply #7 - Posted 2013-06-24 21:36:25 »

In your block class, it might just be best to have the parsing of the string in there as a constructor

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public class Block
{
   int x, y, blocktype;

   public Block(String data)
   {
       //we make sure to use regex so add a little bit of lenience to parsing
      String[] parsedData = data.split("/[, ]+/");

       this.x = Integer.parseInt(parsedData[0]);
       this.y = Integer.parseInt(parsedData[1]);
       this.blocktype = Integer.parseInt(parsedData[2]);
   }
}


If ever it throws an exception, then we just won't add the block to your array and the garbage collector will pick it up.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
ArrayList<Block> blocks = new ArrayList<Block>();

try (BufferedReader br = new BufferedReader(new FileReader(filepath)))
{
    String line;
    while ((line = br.readLine()) != null)
    {
        try
        {
            Block b = new Block(line);
            blocks.add(b);
        }
    }
}


Thanks to try-with-resources, we can easily jump through a bufferedreader and have it automatically close when we're done.  It keeps the code looking a lot cleaner.
Offline ags1

JGO Ninja


Medals: 46
Projects: 2
Exp: 5 years


Make code not war!


« Reply #8 - Posted 2013-06-24 23:26:03 »

StringTokenizer sounds good... but I would do this because I always forget about it:

for (String line : fileAsString.replace("\r", "").split("\\n") {
   String[] nums = line.split(",");
   Block b = new Block(Long.parseLong(nums[0]), Long.parseLong(nums[1]), Long.parseLong(nums[2]));
   blockHandler.handleBlock(b);
}

Offline ags1

JGO Ninja


Medals: 46
Projects: 2
Exp: 5 years


Make code not war!


« Reply #9 - Posted 2013-06-24 23:28:19 »

StringTokenizer sounds good... but I would do this because I always forget about it:

for (String line : fileAsString.replace("\r", "").split("\\n") {
   String[] nums = line.split(",");
   Block b = new Block(Long.parseLong(nums[0]), Long.parseLong(nums[1]), Long.parseLong(nums[2]));
   blockHandler.handleBlock(b);
}

@nhydock, why build lenience into file reading. Keep it strict and reject all deviation, I say!

Why did I quote myself... I thought I was editing my last post  Huh

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline davidc

Senior Member


Medals: 5
Projects: 2



« Reply #10 - Posted 2013-06-25 03:17:45 »

@nhydock, why build lenience into file reading. Keep it strict and reject all deviation, I say!

I agree - just ignoring errors and hoping they go away without affecting the rest of the program is just madness.

Building robust code is not about hiding errors, but finding out what caused them.
Offline UprightPath
« Reply #11 - Posted 2013-06-25 15:58:56 »

I agree - just ignoring errors and hoping they go away without affecting the rest of the program is just madness.

Building robust code is not about hiding errors, but finding out what caused them.

If it's a save function, then the format of the save file should be well known. As such, any deviation from the well known pattern is likely to indicate either a failure to correctly save the data or else a failed edit by an outside entity. If you're worried about the first of the two options, then you need to identify the failure to save at save time rather than load time. There are several methods by which you can do this (Saving then loading and checking if the load resulted in the same game state, creating a check-sum or something off the expected save file, etc..)

The only reason you'd need a robust loader is if you support multiple versions of the load function based on previous versions of the save function (Backwards compatibility). In that case, you only need enough information to figure out which loader you should use rather than making a robust error checker that allows you to do it.

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CogWheelz (12 views)
2014-08-01 22:53:16

CogWheelz (14 views)
2014-08-01 22:51:43

CopyableCougar4 (15 views)
2014-08-01 19:37:19

CogWheelz (19 views)
2014-07-30 21:08:39

Riven (27 views)
2014-07-29 18:09:19

Riven (16 views)
2014-07-29 18:08:52

Dwinin (14 views)
2014-07-29 10:59:34

E.R. Fleming (35 views)
2014-07-29 03:07:13

E.R. Fleming (13 views)
2014-07-29 03:06:25

pw (44 views)
2014-07-24 01:59:36
Resources for WIP games
by CogWheelz
2014-08-01 18:20:17

Resources for WIP games
by CogWheelz
2014-08-01 18:19:50

List of Learning Resources
by SilverTiger
2014-07-31 18:29:50

List of Learning Resources
by SilverTiger
2014-07-31 18:26:06

List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!