[英]In Java I need to read a text file and put each line in a separate array. But every time I read the text file I cannot split the lines
In Java I need to read a text file(the file contains three lines and I need to put each line in a double arrray). 在Java中,我需要读取一个文本文件(该文件包含三行,并且需要将每行放在一个双行进位中)。 But I cant split the line.
但是我不能分界线。 This is the code I have so far.
这是我到目前为止的代码。 But I don't know how to proceed:
但我不知道如何进行:
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);
}
}
I think you want t read a file of numbers and put it inside Array of doubles, If that so you can see this code: 我认为您不希望读取数字文件并将其放入双精度数组中,如果那样,则可以看到以下代码:
Note: I have used
try-with-resource
to prevent source leaks.注意:我使用
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);
}
}
}
File Sample: 文件样本:
343
6787
19
22
58
0
Output Sample: 输出样本:
[343.0, 6787.0, 19.0, 22.0, 58.0, 0.0]
There is no need to add text together, So if you want to just display the content of the file line-by-line, try this: 无需一起添加文本,因此,如果您只想逐行显示文件的内容,请尝试以下操作:
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);
}
}
}
}
File Sample: 文件样本:
343
6787
19
22
58
0
Output Sample: 输出样本:
343
6787
19
22
58
0
Here is how you can do this using Java 8 features: 使用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);
}
}
You can make this a bit more general by parameterizing the line transformation, see here https://gist.github.com/sorokod/818ccd65cad967cdecb7dbf4006e4fa0 您可以通过参数化线转换使它更通用,请参见此处https://gist.github.com/sorokod/818ccd65cad967cdecb7dbf4006e4fa0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.