在Java中我需要读取一个文本文件(该文件包含三行,我需要将每行放在一个双层arrray中)。但是我不能分开这条线。这是我到目前为止的代码。但我不知道如何继续:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class FedEx {
public static void main(String[] args) throws Exception
{
//Read the file
FileReader file = new FileReader("info.txt");
BufferedReader br = new BufferedReader(file);
String text = " ";
String line = br.readLine();
while(line != null)
{
text += line;
line = br.readLine();
}
//Print the text file.
System.out.println(text);
}
}
答案 0 :(得分:1)
我想你想读一个数字文件并把它放在双打数组中,如果是这样你可以看到这段代码:
注意:我使用
try-with-resource
来防止源泄漏。
public class FedEx {
public static void main(String[] args) throws Exception {
// Read the file
try (BufferedReader br = new BufferedReader(new FileReader("info.txt"))) {
String line;
List<Double> doubles = new ArrayList<>();
while ((line = br.readLine()) != null) {
doubles.add(Double.parseDouble(line));
}
System.out.println(doubles);
}
}
}
文件示例:
343
6787
19
22
58
0
输出样本:
[343.0, 6787.0, 19.0, 22.0, 58.0, 0.0]
无需一起添加文本,因此,如果您只想逐行显示文件内容,请尝试以下操作:
public class FedEx {
public static void main(String[] args) throws Exception {
// Read the file
try (BufferedReader br = new BufferedReader(new FileReader("info.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
文件示例:
343
6787
19
22
58
0
输出样本:
343
6787
19
22
58
0
答案 1 :(得分:0)
以下是使用Java 8功能执行此操作的方法:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FileLineByLine {
private static List<Double> file2doubles(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
return stream.map(Double::parseDouble).collect(Collectors.toList());
}
}
public static void main(String args[]) throws Exception {
List<Double> doubles = file2doubles(args[0]);
System.out.println(doubles);
}
}
您可以通过参数化线变换使其更加通用,请参阅此处https://gist.github.com/sorokod/818ccd65cad967cdecb7dbf4006e4fa0