简体   繁体   中英

Java Binary I/O Method Stream

I'm pretty confused on file streaming. I have an input file stream method that will load the file, I can't figure out how to then use the file in another method. The files has one UTF string and two integers. How can I now use each of these different int or strings in a main method?

public static void  dataStream() throws IOException { 

    try (DataInputStream input = new DataInputStream(
            new FileInputStream("input.dat"));
    ) {

        String stringUTF = input.readUTF();
        int firstInt = input.readInt();
        int secondInt = input.readInt();

        //System.out.println("File name: " + fileName);


    }

}

Make an object which happens to do everything you want!

public class MyData {

    private final String data;
    private final int one;
    private final int two;

    public MyData(String data, int one, int two) {
        this.data = data;
        this.one = one;
        this.two = two;
    }

    public String getData() {
        return this.data;
    }

    //etc
}

And return that from your method:

public static MyData dataStream() throws IOException { 
    try (DataInputStream input = new DataInputStream(new FileInputStream("input.dat"))) {
        String stringUTF = input.readUTF();
        int firstInt = input.readInt();
        int secondInt = input.readInt();
        return new MyData(stringUTF, firstInt, secondInt);
    }
}

And you can easily utilize this new object:

MyData data = dataStream();
String stringUTF = data.getData(); //tada

Using objects to perform desired behaviors or storing data is basic OOP principles you should utilize in all your programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM