[英]Read file from txt to integer array line by line
我有一个看起来像这样的文本文件:
1 2 3 4 5 8
12 22 5 33 11 56
5 2 3 45 89 45
我提供了一个我尝试过但无法正常工作的代码,因为每次当我尝试将行打印到控制台时,该行看起来都为空。
我尝试使用ArrayList读取文件,但无法正常工作。
BufferedReader bufReader = new BufferedReader(new
FileReader("file1.txt"));
ArrayList<String> listOfLines = new ArrayList<>();
String line = bufReader.readLine();
while (line != null) {
listOfLines.add(line);
line = bufReader.readLine();
System.out.println("full: " + line);
System.out.print("0: " + line.charAt(0));
}
我想逐行从文件读取到数组,例如:[12] [22] [5] [33] [11] [56]
您可以使用流:
Files.lines(Paths.get("file.txt"))
.map(line -> Arrays.stream(line.split(" "))
.map(Integer::valueOf)
.collect(Collectors.toList()))
.collect(Collectors.toList())
这将返回一个List<List<Integer>>
,所有元素均为整数。 如果只想打印每一行的所有元素,则可以用.forEach(System.out::println)
替换最后一行。
如果要将文件每行读入一个数组,可以使用以下代码:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ReadIntArrayFromFile {
public static void main(String[] args) throws IOException {
//enter your path to the file here
File file = new File("src/main/java/integer_array_from_file/file.txt");
//read the lines from the file
List<String> lines = Files.readAllLines(file.toPath());
//create a list of arrays (one array per line)
List<int[]> arrayForEachLine = new ArrayList<int[]>(lines.size());
for (String line : lines) {
//create the array from the line (one array for each line)
int[] array = Stream.of(line.split(" ")).mapToInt(Integer::parseInt).toArray();
//add the array to the list
arrayForEachLine.add(array);
}
//print the arrays
arrayForEachLine.stream().map(array -> Arrays.toString(array)).forEach(System.out::println);
}
}
输出(对于您问题中的示例文件内容)为:
[1, 2, 3, 4, 5, 8]
[12, 22, 5, 33, 11, 56]
[5, 2, 3, 45, 89, 45]
试试这个代码
final String dataFilePath = "C:\\Users\\Desktop\\txt.txt";
ArrayList<String> listOfLines = new ArrayList<>();
List listOfLinesint = new ArrayList<>();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(dataFilePath));
String line = reader.readLine();
while (line != null) {
//System.out.println(line);
listOfLinesint.add(line);
line = reader.readLine();
}
reader.close();
System.out.println(listOfLinesint);
} catch (IOException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.