使用Java将.txt文件转换为数组

kao*_*der 9 java arrays

我有一个包含文档信息的.txt文件(适用于1400个文档).每个文档都有ID,标题,作者,区域和摘要.示例如下所示:

.I 1
.T
experimental investigation of the aerodynamics of a
wing in a slipstream .
.A
brenckman,m.
.B
j. ae. scs. 25, 1958, 324.
.W
experimental investigation of the aerodynamics of a
wing in a slipstream .
  [...]
the specific configuration of the experiment .
Run Code Online (Sandbox Code Playgroud)

我想将其中的每一个放入专用于每个类别的5个阵列中.我在将标题和摘要插入单个数组位置时遇到问题,有人能告诉我这段代码有什么问题吗?我想要做的是在读取".T"后将文本行插入位置x并在找到".A"时停止,当它发生时,将位置增加1以使其填充下一个位置

try{
    collection = new File (File location);
    fr = new FileReader (collection);
    br = new BufferedReader(fr);
    String numDoc = " ";
    int pos = 0;
    while((numDoc=br.readLine())!=null){
        if(numDoc.contains(".T")){
            while((numDoc=br.readLine())!= null && !numDoc.contains(".A")){
                Title[pos] = Title[pos] + numDoc; 
                pos++;
           }

        }
    }
}
catch(Exception e){
     e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

目标是将所有信息都放在一行String中.任何帮助将不胜感激.

Com*_*ass 5

代码演练总是有用的.在将来,你可以使用断点,但我想我知道你为什么得到我认为是空指针异常.

while((numDoc=br.readLine())!=null){
    if(numDoc.contains(".T")){
        while((numDoc=br.readLine())!= null && !numDoc.contains(".A")){
Run Code Online (Sandbox Code Playgroud)

在外面,一切看起来都不错,在这个循环中,事情开始变得疯狂.

            Title[pos] = Title[pos] + numDoc; 
Run Code Online (Sandbox Code Playgroud)

根据您提供的输入,我们将设置:

Title[0]Title[0] + "experimental investigation of the aerodynamics of a"

这仅在Title [0]存在时有效,我不认为它已经初始化了.我们首先通过正确检测空数组值来解决该问题.这可能是关于未初始化的事件的编译器错误或运行时空指针异常.在我的头顶,我想说编译器错误.

所以无论如何,我们将解决处理null Title [pos]的问题.

while((numDoc=br.readLine())!=null){
    if(numDoc.contains(".T")){
        while((numDoc=br.readLine())!= null && !numDoc.contains(".A")){
            if(Title[pos] != null) {
                Title[pos] = Title[pos] + numDoc; 
            }
            else {
                Title[pos] = numDoc;
            }
            pos++;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我们进行另一次演练时,我们将获得以下数组值

标题[0] = a的空气动力学实验研究

标题[1] =滑流中的翼.

如果这是有意的,那么这很好.如果你想要标题,那么你移出pos++while循环.

while((numDoc=br.readLine())!=null){
    if(numDoc.contains(".T")){
        while((numDoc=br.readLine())!= null && !numDoc.contains(".A")){
            if(Title[pos] != null) {
                Title[pos] = Title[pos] + " " + numDoc; // add a space between lines
            }
            else {
                Title[pos] = numDoc;
            }
       }
       pos++;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们得到:

标题[0] =滑流中机翼的空气动力学实验研究.

您可能希望修剪输入,但这应该涵盖我可以看到的两个潜在错误.


Sco*_*ter 0

pos因为每次添加非 .A 行时都会递增,所以这些行不会进入 .A 的同一元素Title。我认为您想等到pos读完 .A 行后再增加。