java - 从文件中读取并将第一个整数存储为字符串,其余的存储为整数
问题描述
我正在尝试读取文件并存储单个整数,但将文件中的第一个整数转换为字符串。我已经能够读取该文件,但我正在努力分别存储整数。我想在程序中使用它们。
该文件每行有三个整数,由空格分隔。
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);
}
}
解决方案
您可以使用以下方法。迭代行,拆分它,首先作为字符串,其他两个作为整数(假设你有数据作为
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();
}
输出是:
推荐阅读
- javascript - 在事件回调函数内调用的 JavaScript 类构造函数不会将参数的值分配给属性。问题是为什么?
- c++ - 空闲列表分配器标头元数据
- c++ - 如何在 ImGui 中更改 InputText 的文本颜色?
- google-colaboratory - 如何从 google colab 加载保存的 h5 文件并在 PC 中使用
- java - Singletop 活动不会在按下后退按钮时恢复
- javascript - 从异步函数中隐藏 ng-repeat 列表中的单个跨度
- php - WooCommerce:从产品变体中获取自定义字段并将其显示在“附加信息区域”
- javascript - 部署时 Cloud Function 不会保存到 Firestore
- html - 如何获取 .html 网页中使用的数据?
- javascript - 为什么我有一个错误'无法读取未定义的属性'地图'?