我需要阅读的文件到数组long[]
,这样的结果将是相同创建新实例:如何读取.txt文件以长[] JAVA?
long [] y = new long[] {
500, 300, 16800, 35200,
60000, 50000, 2200, 2200, 29500
};
我该怎么办呢?
我需要阅读的文件到数组long[]
,这样的结果将是相同创建新实例:如何读取.txt文件以长[] JAVA?
long [] y = new long[] {
500, 300, 16800, 35200,
60000, 50000, 2200, 2200, 29500
};
我该怎么办呢?
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();
}
试试。难看,但应该工作
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();
您可以使用Scanner
,一个List<Long>
和一对循环(一个读long
(S)为List
然后第二至List
转换为数组)的东西像 -
public static long[] readFile(String filePath) {
List<Long> al = new ArrayList<Long>();
File f = new File(filePath);
Scanner scanner = null;
try {
scanner = new Scanner(f);
while (scanner.hasNextLong()) {
al.add(scanner.nextLong());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
long[] ret = new long[al.size()];
for (int i = 0; i < al.size(); i++) {
ret[i] = al.get(i);
}
return ret;
}
使用以前的答案为基础:
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填充列表中的数字。扫描仪对于较大的输入可能有点慢。我建议分词 此外,由于我们没有分配任何额外的对象(包装为基本类型),并没有多余的临时数据结构(除标记生成器内部)
// 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());
}
你有没有尝试任何事情,这将是更多的内存有效? – Reimeus 2014-08-27 13:07:30
你将在txt-File中使用哪种格式? CSV? – treeno 2014-08-27 13:07:40
好吧,打开一个阅读器,阅读文本,按分隔符分割并将每个值解析为一长整数:-) – Leo 2014-08-27 13:11:24