[英]Reading a file and saving each line into a variable
For a project of mine, I'm trying to read a file of Integers and save each line into a file.对于我的一个项目,我正在尝试读取一个整数文件并将每一行保存到一个文件中。 Each of the files I'm reading have a different amount of lines.
我正在阅读的每个文件都有不同数量的行。
The file would look like该文件看起来像
17
17
7272
6161
1111
6363
9595
100100
Is there a way I can use a loop and save the value in a different variable for each line?有没有办法可以使用循环并将每行的值保存在不同的变量中?
Assuming you just want to take a line and copy it into another file, here you go: Reading the file as long as there are lines and just change System.out.println(line);
假设您只想取一行并将其复制到另一个文件中,这里是 go: 只要有行就读取文件,只需更改
System.out.println(line);
(line 16) to create and write to the file (and there just add an incrementing index (like index++
executed at the end of "while") to the filename and pass "line" to the write function). (第 16 行)创建和写入文件(并且只需在文件名中添加一个递增索引(如在“while”末尾执行的
index++
)并将“line”传递给 write 函数)。
The only thing that is important: close the BufferedReader and the FileWriter!!唯一重要的是:关闭 BufferedReader 和 FileWriter!!
To prevent getting deleted by a bot the code from the links:为了防止被机器人删除,链接中的代码:
Create a Collection to capture your values.创建一个集合来捕捉您的价值观。 We can use a List so we maintain the input order.
我们可以使用 List 来维护输入顺序。
List<Integer> list = new ArrayList<>();
Create a mechanism for reading from the file.创建从文件中读取的机制。 A common option is a Scanner.
一个常见的选项是扫描仪。 The Scanner is Autoclosable so we'll put it in a try-with-resources block so we don't have to close it ourselves.
Scanner 是可自动关闭的,所以我们将它放在一个 try-with-resources 块中,这样我们就不必自己关闭它。
try (Scanner scanner = new Scanner(new File(fileName))) {
... do stuff ...
}
While the Scanner has values, read a value and add it to the List.当 Scanner 有值时,读取一个值并将其添加到列表中。
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
In sum...总共...
List<Integer> list = new ArrayList<>();
try (Scanner scanner = new Scanner(yourFileName)) {
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.