【发布时间】:2017-02-23 01:48:36
【问题描述】:
我正在尝试从名为 boyNames.txt 的文件中获取名称。其中包含 1000 个男孩的名字。例如,文件中的每一行如下所示:
- 德文
- 克里斯
- 汤姆
目标只是尝试读取名称,但我在 java.util 包中找不到允许我仅获取文件 boyName.txt 中的名称的方法。
例如,我只想抓住 Devan,然后是 Chris,然后是 tom。
不是“1. Devan”和“2. Chris”。
问题是 hasNextLine 抓取了整行。我不想要“1”。部分。
所以我只想读取 Devan、Chris、Tom 或将其存储在 String 类型的变量中。有谁知道这是怎么做到的吗?我试过 HasNext(),但没用。
这里是代码,所以你可以得到一个视觉效果:
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileInputStream;
public class PracticeWithTxtFiles {
public static void main(String[] args){
PrintWriter outputStream = null;
Scanner inputStream = null;
try{
outputStream = new PrintWriter(new FileOutputStream("boys.txt")); //opens up the file boys.txt
inputStream = new Scanner(new FileInputStream("boyNames.txt"));//opens up the file boyNames.txt
}catch(FileNotFoundException e){
System.out.println("Problem opening/creating files");
System.exit(0);
}
String names = null;
int ssnumbers= 0;
while(inputStream.hasNextLine())//problem is right here need it to just
// grab String representation of String, not an int
{
names = inputStream.nextLine();
ssnumbers++;
outputStream.println(names + " " + ssnumbers);
}
inputStream.close();
outputStream.close();
}
}
【问题讨论】:
-
阅读整行,然后剪掉你不想要的部分。这不是很明显吗?您是否希望文件阅读器能够神奇地为您解释文件中的数据并决定什么对您来说很重要?
-
大声笑,不,我没有。你显然无法阅读。我知道它没有。 hasNextLine() 读取整行。我只是想知道是否有一种方法可以获取字符串的字符串表示形式。所以它只会抓住字符串。就像 hasNextInt 只会抓取一个 int 的格式良好的表示。
-
我认为 Java 中没有只读取字母的阅读器,还有其他方法可以实现 - 通过使用正则表达式、替换函数等。