[英]How do you read a text file, line by line, and separate contents of each line in Java?
I was wondering how to go about reading a file, and scanning each line, but separating the contents of each line into a Char variable and into a Double variable. 我想知道如何去读取文件,扫描每一行,但是将每一行的内容分成Char变量和Double变量。
Example: 例:
Let's say we write a code that opens up text file "Sample.txt". 假设我们编写了一个打开文本文件“ Sample.txt”的代码。 To read the first line you would use the following code: 要阅读第一行,请使用以下代码:
while(fin.hasNext())
{
try{
inType2 = fin.next().charAt(0);
inAmount2 = fin.nextDouble();
}
This code basically says that if there is a next line, it will put the next char into inType2 and the next Double into inAmount2. 这段代码基本上说,如果有下一行,它将把下一个字符放入inType2中,并将下一个Double放入inAmount2中。
What if my txt file is written as follows: 如果我的txt文件编写如下:
D 100.00
E 54.54
T 90.99
How would I go about reading each line, putting "D" into the Char variable, and the corresponding Double or "100.00", in this example, into its Double variable. 我将如何读取每一行,将“ D”放入Char变量,并将相应的Double或“ 100.00”(在此示例中)放入其Double变量。
I feel like the code I wrote reads the following txt files: 我觉得我编写的代码读取以下txt文件:
D
100.00
E
54.54
T
90.99
If you could please provide me with an efficient way to read lines from a file, and separate according to variable type, I'd greatly appreciate it. 如果可以的话,请为我提供一种有效的方式来读取文件中的行并根据变量类型进行分隔,我将不胜感激。 The Sample.txt will always have the char first, and the double second. Sample.txt始终将char放在首位,并将其放在第二位。
-Manny -曼妮
Use BufferedReader
to read line, and then split on whitespace. 使用BufferedReader
读取行,然后在空白处分割。
while((line=br.readLine())!=null){
String[] arry = line.split("\\s+");
inType2 = arry[0];
inAmount2 = arry[1];
}
You can delimit by whitespace
and 您可以按whitespace
分隔,
Scanner scanner = new Scanner(new File("."));
while (scanner.hasNext()) {
//If both on different lines
c = scanner.next().charAt(0);
d = scanner.nextDouble();
//if both on same line
String s = scanner.next();
String[] splits = s.split("\\s+");
if (splits.length == 2) {
c = splits[0].charAt(0);
d = Double.parseDouble(splits[1]);
}
}
scanner.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.