[英]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.
这些文件具有一个UTF字符串和两个整数。 How can I now use each of these different int or strings in a main method?
现在如何在main方法中使用这些不同的int或字符串?
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. 使用对象执行所需的行为或存储数据是您在所有编程中都应使用的基本OOP原则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.