我需要将文件读入数组long[]
,因此结果与创建新实例相同:
long [] y = new long[] {
500, 300, 16800, 35200,
60000, 50000, 2200, 2200, 29500
};
我该怎么做?
答案 0 :(得分:0)
尝试。丑陋,但应该工作
Scanner scanner = new Scanner(new File("myfile.txt"));
String[] numbersStrings = scanner.readLine().split(" ");
long[] numbers = new long[numbersStrings.length];
for (int i = 0; i < numbersStrings.length; i++) {
numbers[i] = Long.parseLong(numbersStrings[i]);
}
scanner.close();
答案 1 :(得分:0)
您可以使用Scanner
,List<Long>
和一对循环(一个将long
(s)读入List
,然后再转换为{ - 1}}到数组),类似于 -
List
答案 2 :(得分:0)
try {
Scanner scanner = new Scanner(new File("myFile.txt"));
long[] values = new long[100];
int i = 0;
while (scanner.hasNextLong()) {
values[i] = scanner.nextLong();
i++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 3 :(得分:0)
使用上一个答案作为基础:
try (Scanner scanner : new Scanner(new File("myfile.txt")) {
List<Long> numbers = new ArrayList<>();
while (scanner.hasNextLong()) {
numbers.add(scanner.nextLong());
}
Long[] value = numbers.toArray(new Long[numbers.size()]);
// or:
long[] values = new long[numbers.size()];
int i = 0;
for (Long n : numbers) {
values[i] = n;
++i;
}
}
Long
。ArrayList
中,因为我们不知道文件中的数量。转换ArrayList
有点棘手:
Long
可以转换为long
(以及long
至Long
),但这不适用于数组:Long[]
是不是long[]
。Long
数组。 long[]
数组,并使用for-each填充列表中的数字。答案 4 :(得分:0)
对于较大的输入,扫描仪可能有点慢。我推荐tokenizer 此外,这将更有效,因为我们没有分配任何额外的Object(基元的包装器),也没有额外的临时数据结构(除了tokenizer内部)
// Read the file into the string.
// WARNING: This will throw OutOfMemoryException on very large files
// To handle large file you will need to wrap the file into a buffer and read it partially.
// Also this method is present only in Java 7+ . If you're on 6, just use regular file reading
byte[] fileContent = Files.readAllBytes(Paths.get(path));
String str = new String(fileContent, encoding);
// The second parameter is the delimiter. If your data is separated by space, this will work.
// Otherwise (ex. by comma - ,) you will need to supply it here
StringTokenizer tokenizer = new StringTokenizer(str," ");
long[] values = new long[tokenizer.countTokens()];
int idx = 0;
while(tokenizer.hasMoreTokens()) {
values[idx++] = Long.parseLong(tokenizer.nextToken());
}