我如何阅读.text文件到long [] JAVA?

时间:2014-08-27 13:05:00

标签: java arrays long-integer

我需要将文件读入数组long[],因此结果与创建新实例相同:

long [] y = new long[] { 
   500, 300, 16800, 35200, 
   60000, 50000, 2200, 2200, 29500
}; 

我该怎么做?

5 个答案:

答案 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)

您可以使用ScannerList<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;
  }

}
  • try-with-resources用于在您完成阅读后关闭扫描程序和文件。
  • Scanner是一个可以阅读各种内容的类,其中可以阅读Long
  • 我们需要将值存储在ArrayList中,因为我们不知道文件中的数量。

转换ArrayList有点棘手:

  • 使用自动装箱Long可以转换为long(以及longLong),但这不适用于数组:Long[]是不是long[]
  • 第一个表单使用toArray方法,该方法返回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());
}