Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (107)
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  
  Reading/Writing To/From a text file  (Read 1169 times)
0 Members and 1 Guest are viewing this topic.
Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Posted 2011-12-05 04:59:16 »

I am trying to make a save system for my text-based game, and thought it would be a good idea to use a .txt file for saving.

How can I do this?

Thanks.

P.S. If there is a better way than using a .txt file, please let me know.

Check out my website!
Offline gbeebe

Senior Member


Medals: 5
Projects: 1



« Reply #1 - Posted 2011-12-05 05:44:31 »

For reading in my applet... Haven't figured out write yet.

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  
public void readSettings() {
      InputStream inStream = null;
       BufferedReader bufReader = null;
       String ln;
       
       
       try {
          inStream = getClass().getResourceAsStream("res/settings.txt");
          bufReader = new BufferedReader(new InputStreamReader(inStream));
           while (null != (ln = bufReader.readLine())) {
              //Display the line of text
               System.out.println(ln);

           }
       }catch (Exception e) {
          e.printStackTrace();
       }finally {
          try {
              if (bufReader != null) bufReader.close();
              if (inStream != null) inStream.close();
          }catch (IOException e) {
             e.printStackTrace();
          }
       }      
   }
Offline ra4king

JGO Kernel


Medals: 340
Projects: 2
Exp: 5 years


I'm the King!


« Reply #2 - Posted 2011-12-05 11:43:55 »

That's because you can't write to a file when running an unsigned applet, but I believe the OP is asking about a console app.

How about using the new features in Java 7?

1  
2  
3  
4  
5  
6  
7  
8  
public void readSettings() {
    try(BufferedReader reader = new BufferedReader(getClass().getResourceAsStream("settings.txt")) {
        String line;
        while((line = reader.readLine()) != null) {
            //deal with the line
       }
    }
}


Also it might be easier to use Scanner, since it offers a bit more useful methods (especially when reading from a settings file):
1  
2  
3  
4  
5  
6  
7  
8  
9  
public void readSettings() {
    Scanner scanner = new Scanner(getClass().getResourceAsStream("settings.txt"));
   
    while(scanner.hasNextLine()) {
        //read from the Scanner
   }
   
    scanner.close();
}

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

JGO Kernel


Medals: 145
Projects: 4
Exp: 14 years


Esoteric Software


« Reply #3 - Posted 2011-12-05 12:09:41 »

I'm spoiled by FileHandle in libgdx...
1  
2  
3  
FileHandle file = Gdx.files.internal("stuff.txt");
file.writeString("mooooo", true); // true means overwrite, false is append
String text = file.readString();

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #4 - Posted 2011-12-05 15:11:57 »

Ra4king, in the line where your comment says //read from the scanner, how can I take this data that it reads and store it line-by-line to variables? I want line 1 to be something, line 2 to be another, etc and I can't figure out a way to not have them overlap.

Check out my website!
Offline h3ckboy

JGO Coder


Medals: 5



« Reply #5 - Posted 2011-12-05 17:28:22 »

variable = scanner.next()

basically it'll go through all the lines and then get all the lines as it goes through.

not 100% on this though, u may wanna test it, cause I just check the javadoc really quick(FYI, that is where you will find the solutions to a lot of your problems Wink )
Offline Nyhm

Senior Member


Medals: 3
Projects: 1


Island Forge


« Reply #6 - Posted 2011-12-05 21:46:20 »

This is quick-and-dirty, but I think it clarifies what StonePickaxes is asking. If you absolutely positively know you have three settings (three lines) in your file:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
class MySettings {

    private final String settingA;
    private final String settingB;
    private final String settingC;

    MySettings() {
      Scanner scanner = new Scanner(getClass().getResourceAsStream("settings.txt"));
   
      settingA = scanner.nextLine();
      settingB = scanner.nextLine();
      settingC = scanner.nextLine();
   
      scanner.close();
    }
}

Island Forge: Create Islands with Stories for Others to Explore!
Free-to-Play with Membership and Upgrade options!
Offline Z-Man
« Reply #7 - Posted 2011-12-05 23:37:18 »

How about using the new features in Java 7?
It's not backwards compatible Tongue although the OP is probably not worried about this at the moment. Just be warned, try-with-resources is a Java 7 thing.
Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #8 - Posted 2011-12-08 22:07:44 »

This is quick-and-dirty, but I think it clarifies what StonePickaxes is asking. If you absolutely positively know you have three settings (three lines) in your file:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
class MySettings {

    private final String settingA;
    private final String settingB;
    private final String settingC;

    MySettings() {
      Scanner scanner = new Scanner(getClass().getResourceAsStream("settings.txt"));
   
      settingA = scanner.nextLine();
      settingB = scanner.nextLine();
      settingC = scanner.nextLine();
   
      scanner.close();
    }
}


Ok, so I'm trying to use this, but I keep getting this error on the getClass() -
Quote
Cannot make a static reference to the non-static method getClass() from the type Object

Any ideas?

EDIT -

So I figured out why, I need to make the class "public void" and not static, but now when I try to call the method via SaL.Load() it doesn't work.

Thanks for the help.

Check out my website!
Offline philfrei
« Reply #9 - Posted 2011-12-08 22:23:36 »

in general, to get rid of the "static vs non-static" error, you can make an instance of the class, and call the method off of that instance. That includes making an instance of the class you are within.

In other words:

1  
2  
3  
4  
5  
6  
7  
8  
9  
 MySettings mySettings = new MySettings();
 
// and later

Scanner scanner = new Scanner(mySettings.getClass().getResourceAsStream("settings.txt"));

// but for what you are doing, this is the more common form:

Scanner scanner = new Scanner(MySettings.class.getResourceAsStream("settings.txt"));


An example of the second form is used in this tutorial.
http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #10 - Posted 2011-12-08 22:38:58 »

Ok, but what does the MySettings represent, the file reading from?

Check out my website!
Offline Nyhm

Senior Member


Medals: 3
Projects: 1


Island Forge


« Reply #11 - Posted 2011-12-08 23:04:29 »

Sorry, the MyClass example was intended as pseudo-code. I encapsulated your various settings in a class. The class's constructor reads the values from the external file. You should add getter methods to the class to expose the setting values. In your overall program you would construct one, and pass it to any methods that need your settings.

Mainly I wanted to exemplify how to use the Scanner to read a few values, but if you want more discussion of the object model, I can go on and on.

EDIT: I re-read your initial post. Are we even on-topic anymore? Regarding reading/writing to a text file, you should read the java.util.Properties API. It's kind of hacky, but will get the job done for simple name-value pairs. (You'll still have the issue of doing this in an Applet, as ra4king mentioned earlier.)

Island Forge: Create Islands with Stories for Others to Explore!
Free-to-Play with Membership and Upgrade options!
Offline philfrei
« Reply #12 - Posted 2011-12-09 01:41:20 »

Quote
Ok, but what does the MySettings represent, the file reading from?

Things seemed to have gotten a bit confused here. I was only addressing the second question about the static vs. non-static error message, and I was using the example code the OP quoted in Post #8. That code is a class definition for the class "MySettings".

If you use "MySettings" (the Name of a class) as the root of a method call, as in "MySettings.class.getResourceAsStream("myFile");"
that is a Static reference, and it tells Java to look in the same directory/location as the compiled class file (as opposed to the Java source file) of the MySettings definition.

Please excuse me if I am undershooting the question. It seems to me that it is possible that the OP wasn't clear on the nature of static vs instance methods and variables, and that this led to his question on post #8.  

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
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 (9 views)
2014-07-30 21:08:39

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

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

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

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

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

pw (42 views)
2014-07-24 01:59:36

Riven (42 views)
2014-07-23 21:16:32

Riven (29 views)
2014-07-23 21:07:15

Riven (30 views)
2014-07-23 20:56:16
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

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24: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!