在 Java 中读取和写入整数 from/to 文件
Reading and writing Integers from/to file in Java
我刚刚创建了用于将整数从文件读取到 Set 中的应用程序,我有一个问题,当我的输入文件中有数字 -5 5 2 8 9 1 4 55 70 时,它将数字保存到 Set 中这样-[1, 2, 4, 5, 70, 55, 8, 9],为什么会这样?我希望它避免口是心非 - 这没关系,但我想先保存数字。
Set<Integer> zoznam = new HashSet();
int index = 0;
FileReader fr;
fr = new FileReader(fileName);
String line;
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null) {
System.out.println(line);
String[] items = line.split(" ");
int[] c = new int[items.length];
for (int q = 0; q < items.length; q++) {
c[q] = Integer.parseInt(items[q]);
zoznam.add(c[q]);
}
}
return zoznam;
}
A Set
,一般情况下,不保证任何顺序。如果你想维护你需要使用专门实现的顺序,例如,a LinkedHashSet
,保留插入顺序。
我刚刚创建了用于将整数从文件读取到 Set 中的应用程序,我有一个问题,当我的输入文件中有数字 -5 5 2 8 9 1 4 55 70 时,它将数字保存到 Set 中这样-[1, 2, 4, 5, 70, 55, 8, 9],为什么会这样?我希望它避免口是心非 - 这没关系,但我想先保存数字。
Set<Integer> zoznam = new HashSet();
int index = 0;
FileReader fr;
fr = new FileReader(fileName);
String line;
BufferedReader br = new BufferedReader(fr);
int i = 0;
while ((line = br.readLine()) != null) {
System.out.println(line);
String[] items = line.split(" ");
int[] c = new int[items.length];
for (int q = 0; q < items.length; q++) {
c[q] = Integer.parseInt(items[q]);
zoznam.add(c[q]);
}
}
return zoznam;
}
A Set
,一般情况下,不保证任何顺序。如果你想维护你需要使用专门实现的顺序,例如,a LinkedHashSet
,保留插入顺序。