Java-Gaming.org Hi !
Featured games (81)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (119)
games submitted by our members
Games in WIP (577)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  How do you read an int from a txt file.  (Read 3354 times)
0 Members and 1 Guest are viewing this topic.
Offline IDontCare

Junior Newbie





« Posted 2012-08-02 13:29:49 »

A friend and I were considering storing game information in a txt file
(especially arrays)

I found a tutorial on reading from a txt file ( http://www.homeandlearn.co.uk/java/read_a_textfile_in_java.html )

But we haven't figured out how to read an int stored.

Any help would be greatly appreciated.

IDC
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 816
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #1 - Posted 2012-08-02 13:45:06 »

offtopic:

Please 'unlearn' everything you learned form that tutorial. There is so many wrong with it, it's hard to start explaining. Reading a file to count the number of lines, then creating a String[n], then filling the String[] by reading the file again, is pretty much the most braindead way to read the contents of a file.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Cero
« Reply #2 - Posted 2012-08-02 14:16:59 »

Check out this thread for numerous ways to do it properly: http://www.java-gaming.org/topics/read-file-to-string-can-you-do-faster/24639/msg/208363/view.html

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

Junior Newbie





« Reply #3 - Posted 2012-08-02 14:31:04 »

Hi all,
    Thanks  Cero + Riven for your answers. Do you have a link to a better tutorial than the one i quoted? Im a new programmer to Java but have programmed with QBasic and QB64 previously. I decided to learn Java because its the modern way of computing with multi platform capabilities.
IDC.
Offline davedes
« Reply #4 - Posted 2012-08-02 14:45:10 »

You can use the Scanner class to read different data types:
http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Another common method is to strip line space and parse the string as an integer
1  
2  
3  
4  
5  
6  
try {
    int num = Integer.parseInt(myText.strip());
    ... do something ...
} catch (NumberFormatException ex) {
    ... handle the error if the text could not be parsed ...
}

Offline Danny02
« Reply #5 - Posted 2012-08-02 15:06:39 »

normally you would want to use a common data format like xml or json, because for these exist a lot of serialisation frameworks.

What serialisation means is, that you just create a simple POJO class(class with only some data) and then you can jsut give an object from this class the serialisation libary and they will automaticly convert it to the data format and back.
Offline The Cure

Senior Newbie





« Reply #6 - Posted 2012-08-02 15:48:47 »

I wrote something a couple days ago. I don't know if i'll use this method to store values (i guess i'll use xml). Anyway, the point is getting a value from a variable in the String type, and then convert it to integer or another type. The method read and search in the txt file for the "<"+"variable name" + "=", so i named this string as "beforeValue", and another String called "afterValue" (just what i have after the value, including the variable to identify the block, in this case the ";"+variable+">").

I have to wrote something like this in my txt file: <x=10;x>  The method will return the "10" in String, and then i convert it to integer.

Code:

1  
2  
3  
4  
5  
    //Data class constructor
    public Data() {
        int x = Integer.parseInt(readValue("C:/myTxt.txt", "x")); //txt path and the variable you're looking for the value.
        System.out.println("The variable value is "+ x); //write 10;
    }


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
    //Read method                                   
    public String readValue(String txtPath, String variable) {
        String value = "0", contents = "", beforeValue = "<" + variable + "=", afterValue = ";" + variable + ">";
        boolean found = false;

        try {
            BufferedReader read = new BufferedReader(new FileReader(txtPath));
            while((contents = read.readLine()) != null && !found){
                if (contents.contains(beforeValue)) {
                    value = contents.substring(contents.indexOf(beforeValue) + beforeValue.length(), contents.indexOf(afterValue));
                    found = true;
                }
            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        return value;
    }


Obs: The txt file content also works in sequence:

 E.g1 (same line): <x=10;x> <y=30;y> <z=50;z>
 E.g2 (line breaking): <x=10;x>
                                  <y=30;y>
                                  <z=50;z>

"A candle loses nothing by lighting another candle" - Erin Majors
Offline philfrei
« Reply #7 - Posted 2012-08-02 16:02:34 »

A "Data Stream" might be sufficient for your purposes.

Quote
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the DataInput interface or the DataOutput interface. This section focuses on the most widely-used implementations of these interfaces, DataInputStream and DataOutputStream.

Tutorial here:
http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html




"It's after the end of the world! Don't you know that yet?"
Offline jonjava
« Reply #8 - Posted 2012-08-02 19:21:16 »

You've got it the wrong way around. A more correct way of saying is how to read text from an int - but even this isn't exactly right. What you actually need to do is figure out how to read bytes as text.

You might think that it's straightforward to just read everything as text. But this isn't the case. The most straightforward way is dealing with bytes. Fortunately, people have been for decades trying to figure out a common way to convert bytes into readable text - The stuff that they figured out were 'Character Encodings'.

IIRC Java by default used UTF-8 which is compatible with ASCII (which is what basic notepad used (I think)).

You will never understand wth is going on if you do not realize that "text" is an illusion. If you figure out how to read and write bytes into files you can EASILY convert the bytes into text based on whatever encoding you choose.

Offline Roquen
« Reply #9 - Posted 2012-08-02 19:25:19 »

Sadly the illusion involves convert some text representations into the actual number that it represents.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #10 - Posted 2012-08-02 19:32:51 »

so actually its pretty simple to read a text file:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
public void readFile(File file) {
    BufferedReader read = null;
    try {
        read = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = null;
        while((line = read.readLine()) != null) {
            // Do stuff with "line" here. "line" is the read line.
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (read != null) {
            read.close();
        }
    }
}


And converting Strings to ints is easy too:
1  
int integer = Integer.parseInt("-5");

And the other way around is easy too:
1  
String string = "" + integer; // or "Integer.toString(integer);"

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline jonjava
« Reply #11 - Posted 2012-08-02 19:39:44 »

Sadly the illusion involves convert some text representations into the actual number that it represents.

What do you mean?

Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #12 - Posted 2012-08-02 19:41:46 »

Sadly the illusion involves convert some text representations into the actual number that it represents.

What do you mean?

I think (!):
For programmers: String->Integer

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline jonjava
« Reply #13 - Posted 2012-08-02 19:44:08 »

What? :S

Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #14 - Posted 2012-08-02 19:56:54 »

Erm... convert a String into an Integer?

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline Danny02
« Reply #15 - Posted 2012-08-02 20:13:06 »

There is also the new way, since the File class is somewhat deprecated.

1  
        Files.readAllLines(Paths.get("./test.txt"), Charset.defaultCharset());
Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #16 - Posted 2012-08-02 20:26:29 »

since the File class is somewhat deprecated.
Tell me more about that, I've never heard of something like that Shocked

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline Damocles
« Reply #17 - Posted 2012-08-02 20:29:30 »

Files and programs and Application-windows are outdated. (so 1990s)

Now there are only "could-drops", "apps" and "Metro-Tabs" and touchscreen GUI metaphors for mouse-users...

and no more ip adresses like 192.168.0.200
now its like  5BF8:981A:8139:AB08:C3G0:0182:321B:213F

what has the poor computer become?

Offline jonjava
« Reply #18 - Posted 2012-08-02 22:04:57 »

since the File class is somewhat deprecated.
Tell me more about that, I've never heard of something like that Shocked

java 1.4.2 came out with java.nio - IIRC, however, java.nio simply enhances the old java.io so the File class isn't deprecated. But, yeah, nio is better.

http://java.dzone.com/articles/java-nio-vs-io

Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #19 - Posted 2012-08-03 00:03:44 »

He is talking about NIO2 which came out with Java 7. This new framework, found under java.nio.files, is a better system to access files and folders on the file system than the old Java IO. However, this does not mean Java IO is deprecated Wink

Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #20 - Posted 2012-08-03 08:59:21 »

since the File class is somewhat deprecated.
Tell me more about that, I've never heard of something like that Shocked

java 1.4.2 came out with java.nio - IIRC, however, java.nio simply enhances the old java.io so the File class isn't deprecated. But, yeah, nio is better.

http://java.dzone.com/articles/java-nio-vs-io
Woah lolz... Who would do this with ByteBuffers? What I'd do is implement my own ByteBufferInputStream then, and let that one use java.nio buffer reading and use the java.io classes like BufferedReader to read things. But srsly... why would anyone do this with ByteBuffers, such a hard way?!?

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline jonjava
« Reply #21 - Posted 2012-08-03 09:43:26 »

He is talking about NIO2 which came out with Java 7.

Why would anyone use Java7? :l

Offline davedes
« Reply #22 - Posted 2012-08-03 13:03:42 »

Only on JGO will a newbie question like "How do you parse an integer?" turn into a discussion on NIO buffers, JSON serialization, new Java 7 features, binary data streams...

 Grin

Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #23 - Posted 2012-08-03 15:22:43 »

The question is: why wouldn't anyone use Java 7? Wink

Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #24 - Posted 2012-08-03 18:26:42 »

Kind of offtopic now... but how's the state with java 7 on Linux now? Does it crash and give strange exceptions, or other weird stuff I've heard?

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #25 - Posted 2012-08-03 18:39:51 »

It's already pushed to www.java.com so it should be very stable by now.

Offline jonjava
« Reply #26 - Posted 2012-08-03 18:48:35 »

It's already pushed to www.java.com so it should be very stable by now.
..should be..

Personally I won't touch it for years if I can avoid it. :]

Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #27 - Posted 2012-08-03 18:54:52 »

Ok then, avoid the speed optimizations Smiley

Offline matheus23

JGO Kernel


Medals: 109
Projects: 3


You think about my Avatar right now!


« Reply #28 - Posted 2012-08-03 20:06:30 »

Ok then, avoid the speed optimizations Smiley
That is the main reason for me to change... (and those little underscores which you can put into numbers :> and those 00011001b bit assigns :>)

But what is keeping me is the unstability... I'm kind of "afraid" of moving to Java 7 ... :/ Though they got the new GC and the other stuff and so on...

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Offline ra4king

JGO Kernel


Medals: 350
Projects: 3
Exp: 5 years


I'm the King!


« Reply #29 - Posted 2012-08-03 20:11:25 »

I've been using it for a year and no problems.....

Pages: [1] 2
  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.

Longarmx (49 views)
2014-10-17 03:59:02

Norakomi (38 views)
2014-10-16 15:22:06

Norakomi (31 views)
2014-10-16 15:20:20

lcass (34 views)
2014-10-15 16:18:58

TehJavaDev (65 views)
2014-10-14 00:39:48

TehJavaDev (65 views)
2014-10-14 00:35:47

TehJavaDev (55 views)
2014-10-14 00:32:37

BurntPizza (72 views)
2014-10-11 23:24:42

BurntPizza (43 views)
2014-10-11 23:10:45

BurntPizza (84 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

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

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

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
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!