我正在尝试从txt文件中读取信息。文本文件采用以下格式:
1 I like programming. 2 "but I am new at it" 3 -so I need to go
4 on web sites, 5 to get 6 help.
7 I appreciate any help you could give me. 8 Thanks.
我想按如下方式显示它,同时在每个数字之前添加" Chap",用于章节。
Chap 1 I like programming.
Chap 2 "but I am new at it"
Chap 3 -so I need to go
Chap 4 on web sites,
Chap 5 to get
Chap 6 help.
Chap 7 I appreciate any help you could give me.
Chap 8 Thanks.
这是我到目前为止所做的:
public class ReadAFile {
public static void main(String[] args) throws IOException {
// Get bible book names, chapters and verses
File fileIn = new File("t.txt");
Scanner inputFile = new Scanner(fileIn);
while(inputFile.hasNext())
{
// Read all lines from the file.
String line = inputFile.nextLine();
System.out.println(line);
String[] tokens = line.split(" ");
for(int i = 0; i < tokens.length; i++)
{
if(tokens[i].matches("^-?\\d+$")) // I'mm using this to try to find the numbers in the txt file
{
for(int p = 0; p < tokens.length; p++)
{
System.out.println(tokens[p]);
}
}
}
}
inputFile.close();
}
}
输出不是我想要的,我无法弄清楚原因。我要么在自己的行上得到每个单词,要么在同一个句子的多行中得到。
答案 0 :(得分:0)
您是否尝试将for循环中的println
切换为print
,然后在打印章节标题时插入新行?
以下是您自己的代码的一部分,已修改。
if(tokens[i].matches("^-?\\d+$")) // I'mm using this to try to find the numbers in the txt file
{
for(int p = 0; p < tokens.length; p++)
{
System.out.print(tokens[p]+ " "); //print
}
System.out.println()//Empty line
}
答案 1 :(得分:0)
数字是否总是从1开始连续?如果是这样,为什么不将它用于您的优势,只需将Scanner的分隔符更改为数字并将其替换为计数器?像这样:
public static void main(String[] args) throws IOException {
// Get bible book names, chapters and verses
File fileIn = new File("t.txt");
Scanner inputFile = new Scanner(fileIn);
inputFile.useDelimiter("\\s*-?\\d+\\s*");
for (int num = 1; inputFile.hasNext(); num++)
{
System.out.println("Chap " + num + " " + inputFile.next());
}
inputFile.close();
}
输出:
Chap 1 I like programming.
Chap 2 "but I am new at it"
Chap 3 -so I need to go
Chap 4 on web sites,
Chap 5 to get
Chap 6 help.
Chap 7 I appreciate any help you could give me.
Chap 8 Thanks.
如果没有,请告诉我,我会处理一些事情来解析并保留它:)