How do you read an int from a txt file.

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

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.

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

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.

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

try {
    int num = Integer.parseInt(myText.strip());
    ... do something ...
} catch (NumberFormatException ex) {
    ... handle the error if the text could not be parsed ...
}

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.

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:


    //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;
    }
    //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 “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.
[/quote]
Tutorial here:
http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html

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.

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

so actually its pretty simple to read a text file:


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:

int integer = Integer.parseInt("-5");

And the other way around is easy too:

String string = "" + integer; // or "Integer.toString(integer);"

What do you mean?

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

What? :S

Erm… convert a String into an Integer?

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


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

Tell me more about that, I’ve never heard of something like that :o

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?

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

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: