【发布时间】:2021-04-22 01:29:49
【问题描述】:
我正在尝试制作一个简单的扫描仪阅读器来读取存储在 C:\Users\james\Desktop\project\files\ 中的 txt,它被称为数据“data.txt”,问题是存储的信息是这样的:
ASSETS 21
CHOROY 12
SHELL 9
所以你可以看到字符串和我想要提取的整数之间的空格是随机的。我试图做到这一点:
public data(String s) //s is the name of the txt "data.txt"
{
if (!s.equalsIgnoreCase("Null"))
{
try {
File text = new File(s);
Scanner fileReader = new Scanner(text);
while (fileReader.hasNextLine())
{
String data = fileReader.nextLine();
String[] dataArray = data.split(" ");
String word = dataArray[0];
String number = dataArray[1];
int score = Integer.parseInt(number);
addWord(word, score);
}
fileReader.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
e.printStackTrace();
}
System.out.println("Reading complete");
}
但是拆分只是在字符串和整数之间有一个空格,所以我想知道如何提取在同一行中用任意数量的空格分隔的两件事。示例:
Line readed: HOUSE 1 -> String word = "HOUSE"; int score = "1";
Line readed: O 5 -> String word = "O"; int score = "5";
【问题讨论】:
-
但是拆分只是在字符串和整数之间有一个空格,所以我想知道如何提取两个用任意数量的空格分隔的东西行。 - 将
data.split(" ")替换为data.split("\\s+")
标签: java file java.util.scanner reader txt