我有很多文字文件(最多20个),每个文件都有这样的内容
21.0|11|1/1/1997
13.3|12|2/1/1997
14.6|9|3/1/1997
并且每个文件大约有300多行。
所以我面临的问题是,如何提取全部且仅提取第一个值 该文件的内容。
例如我想提取值(21.0,13.3,14.6 .....等),这样我就可以决定所有20个文件中的最大数量和最小值。
我已经从我的理解中编写了这段代码来体验文件 但它没有工作
String inputFileName = "Date.txt";
File inputFile = new File(inputFileName);
Scanner input = new Scanner(inputFile);
int count = 0;
while (input.hasNext()){
double line = input.nextDouble(); //Error occurs "Exception in thread "main" java.util.InputMismatchException"
count++;
double [] lineArray= new double [365];
lineArray[count]= line;
System.out.println(count);
for (double s : lineArray){
System.out.println(s);
System.out.println(count);
也是这个
String inputFileName = "Date.txt";
File inputFile = new File(inputFileName);
Scanner input = new Scanner(inputFile);
while (input.hasNext()){
String line = input.nextLine();
String [] lineArray = line.split("//|");
for (String s : lineArray){
System.out.println(s+" ");
}
我希望我很清楚,谢谢
答案 0 :(得分:1)
对于每行文本,检查它是否包含管道符。如果是,请抓取文本的第一部分并将其解析为双倍。
double val = 0.0;
Scanner fScn = new Scanner(new File(“date.txt”));
while(fScn.hasNextLine()){ //Can also use a BufferedReader
data = fScn.nextLine();
if(data.contains("|")) //Ensure line contains "|"
val = Double.parseDouble(data.substring(0, data.indexOf("|"))); //grab value
}
答案 1 :(得分:1)
或者你可以尝试一些流,很酷的东西
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MinMaxPrinter {
public static void main(String[] args) {
final List<String> files = Arrays.asList("file", "names", "that", "you", "need");
new MinMaxPrinter().printMinMax(files);
}
public void printMinMax(List<String> fileNames) {
List<Double> numbers = fileNames.stream()
.map(Paths::get)
.flatMap(this::toLines)
.map(line -> line.split("\\|")[0])
.map(Double::parseDouble)
.collect(Collectors.toList());
double max = numbers.stream().max(Double::compare).get();
double min = numbers.stream().min(Double::compare).get();
System.out.println("Min: " + min + " Max: " + max);
}
private Stream<String> toLines(Path path) {
try {
return Files.lines(path);
} catch (IOException e) {
return Stream.empty();
}
}
}
答案 2 :(得分:0)
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String res = s.split("\\|")[0];
}
}