我有一个输入文件流方法,它将加载一个文件,我只是无法弄清楚如何在另一个方法中使用该文件。该文件有一个UTF字符串和两个整数。我现在如何在主方法中使用这些不同的整数或字符串?让我说我想把三个不同的变量打印到控制台,我该怎么做呢?以下是我尝试过的方法:
public static dataStreams() throws IOException {
int i = 0;
char c;
try (DataInputStream input = new DataInputStream(
new FileInputStream("input.dat"));
) {
while((i=input.read())!=-1){
// converts integer to character
c=(char)i;
}
return c;
return i;
/*
String stringUTF = input.readUTF();
int firstInt = input.readInt();
int secondInt = input.readInt();
*/
}
}
答案 0 :(得分:1)
可能是这些属性的一个容器,如下所示:
public static void main(String [] args) {
DataContainer dContainer = null;
try {
dContainer = dataStreams();
} catch (IOException e) {
e.printStackTrace();
}
//do some logging with properties
System.out.println(dContainer.getFirst());
System.out.println(dContainer.getSecond());
System.out.println(dContainer.getUtf());
}
public static DataContainer dataStreams() throws IOException {
int i = 0;
char c;
try (DataInputStream input = new DataInputStream(
new FileInputStream("input.dat"));
) {
while((i=input.read())!=-1){
// converts integer to character
c=(char)i;
}
String stringUTF = input.readUTF();
int firstInt = input.readInt();
int secondInt = input.readInt();
DataContainer dContainer = new DataContainer(stringUTF, firstInt, secondInt);
return dContainer;
}
}
static class DataContainer {
String utf;
int first;
int second;
DataContainer(String utf, int first, int second) {
this.utf = utf;
this.first = first;
this.second = second;
}
public String getUtf() {
return utf;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}