Search code examples
javasavefile-read2d-games

Reading data from text line by line in java


I'm making a game in Java, but can't figure out how to get information from a text file so that I can load the game. I have the saved files set up so that on every line there is the name of a method in my Main program. What I need to do is to look in a certain line for text and execute the method that the text is referring to.


Solution

  • This should do it. Obviously you'll need to handle exceptions:

    public class FileReaderTest
    {
      public static void main(String[] args) throws IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException
      {
        final FileReaderTest object = new FileReaderTest(); 
    
        final BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/file")));
        for (String line = reader.readLine(); line != null; line = reader.readLine())
        {
          object.getClass().getMethod(line).invoke(object);
        }
      }
    }