首页 > 解决方案 > 从文件中读取并将第一个整数存储为字符串,其余的存储为整数

问题描述

我正在尝试读取文件并存储单个整数,但将文件中的第一个整数转换为字符串。我已经能够读取该文件,但我正在努力分别存储整数。我想在程序中使用它们。

该文件每行有三个整数,由空格分隔。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class arrayListStuffs2 {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter the file name: e.g \'test.txt\'");
    String fileName = sc.nextLine();
    try {
       sc = new Scanner(new File(fileName));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    List<String> listS = new ArrayList<>();
    List<Integer> listI = new ArrayList<>();

    while (sc.hasNextLine()) {
        listI.add(sc.nextInt());
    }
    System.out.println(listI);
 }
}

标签: java

解决方案


您可以使用以下方法。迭代行,拆分它,首先作为字符串,其他两个作为整数(假设你有数据作为

1 2 3
4 5 6
7 8 9

):

List<String> listS = new ArrayList();
List<Integer> listI = new ArrayList();
// try with resource automatically close resources
try (BufferedReader reader = Files.newBufferedReader(Paths.get("res.txt"))) 
{
    reader.lines().forEach(line -> {
        String[] ints = line.split(" ");
        listS.add(String.valueOf(ints[0]));
        listI.add(Integer.parseInt(ints[1]));
        listI.add(Integer.parseInt(ints[2]));
    });

} catch (IOException e) {
    e.printStackTrace();
}

输出是:

在此处输入图像描述


推荐阅读