3 回答
TA贡献1813条经验 获得超2个赞
您可以使用流:
Files.lines(Paths.get("file.txt")) .map(line -> Arrays.stream(line.split(" ")) .map(Integer::valueOf) .collect(Collectors.toList())) .collect(Collectors.toList())
这将返回List<List<Integer>>
所有元素均为整数的 a 。如果您只想打印每一行的所有元素,那么您可以将最后一行替换为.forEach(System.out::println)
.
TA贡献1859条经验 获得超6个赞
试试这个代码
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();
}
TA贡献1744条经验 获得超4个赞
如果您想将文件读入每行一个数组中,您可以使用以下代码:
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]
添加回答
举报