Java: 将行和单词存储到单独的数组列表中,无法打印结果

Java: storing lines and words into separate arraylists, unable to print results

我正在做一个项目,需要我导入一个文本文件,读取文件,并以不同的方式对单词进行排序(即升序、唯一单词等)。到目前为止,我已经能够导入文件并打印它,直到我添加了将列表排序为行和词的命令。

我使用缓冲reader来存储行和词,但是在执行时,我不知道数据是否已经存储在单独的数组列表中,控制台也没有打印存储在 ArrayList wordList 中的单词数。

我哪里错了?

到目前为止,这是我的代码:

public static void main(String[] args)throws IOException{
  if(args.length == 0){
    System.out.println("Error, usage: java ClassName inputfile");
    System.exit(1);
  }
  File randomText = new File(args[0]);
    if(randomText.exists() && randomText.isFile()){
      processFile(randomText);
    } else{
        System.err.println("ERROR: file does not exist");
        System.exit(1);
      }
 }

public static void processFile(File randomText)throws IOException, FileNotFoundException{
  ArrayList<String> lineList = new ArrayList<String>();
  ArrayList<String> wordList = new ArrayList<String>();

  BufferedReader br = new BufferedReader(new FileReader(randomText));
  StringBuffer sb = new StringBuffer();
  String line;
  while((line=br.readLine()) != null){
    sb.append(line);
    sb.append("\n");
    lineList.add(line);
  }
  while((line = br.readLine()) != null){
    wordList = new ArrayList<String>(Arrays.asList(line.split(" |.")));
    }
    System.out.println("Total number of words in the file: " + wordList.size());
    br.close();
}

你不见了wordList.addAll(Arrays.asList(line.split(" |.")));

声明:wordList = new ArrayList<String>(Arrays.asList(line.split(" |.")));这只添加最后一行字

有两种方法可以做到。

  1. 创建另一个 BufferedReader 并添加到 wordList
    BufferedReader br1 = new BufferedReader(new FileReader(randomText));
            while((line = br1.readLine()) != null){
              }
              System.out.println("Total number of words in the file: " + wordList.size());
              br1.close();
          }
  1. 在单个 while 循环中添加到 wordList
public static void main(String[] args) throws FileNotFoundException, IOException {
      if (args.length == 0) {
          System.out.println("Error, usage: java ClassName inputfile");
          System.exit(1);
      }
      File randomText = new File(args[0]);
      if (randomText.exists() && randomText.isFile()) {
          processFile(randomText);
      } else {
          System.err.println("ERROR: file does not exist");
          System.exit(1);
      }
  }
  public static void processFile(File randomText) throws IOException, FileNotFoundException {
      ArrayList<String> lineList = new ArrayList<String>();
      ArrayList<String> wordList = new ArrayList<String>();
      BufferedReader br = new BufferedReader(new FileReader(randomText));
      StringBuffer sb = new StringBuffer();
      String line;
      while ((line = br.readLine()) != null) {
          sb.append(line);
          sb.append("\n");
          lineList.add(line);
          wordList.addAll(Arrays.asList(line.split(" |.")));
      }
      System.out.println("Total number of words in the file: " + wordList.size());
      br.close();
  }

正如其他人所说,您不能重复使用文件 reader。您读取文件一次,然后 reader 对象就完成了。因此,让我们将该文件读入行列表。然后使用该行列表来获取单词列表。

顺便说一下,java.io.File class has been supplanted by the java.nio.file framework, as noted at the end of the File Javadoc’s overview. That note suggests using toPath to convert to a Path 对象。

File file = new File( "/Users/basilbourque/names.txt" );
Path path = file.toPath();

从那个Path对象,我们可以得到一个stream of the lines from that file via Files.lines

Stream < String > lines = Files.lines( path )

例如,尝试将行转储到控制台。

try ( Stream < String > lines = Files.lines( path ) )
{
    lines.forEach( s -> System.out.println( s ) );
}
catch ( IOException e )
{
    e.printStackTrace();
}

我们想把台词收集成一个List。在 Java 16 中,我们使用新方法 Stream#toList 将流捕获到列表的语法更短,而不是显式使用收集器。

List < String > lines = List.of();
try { lines = Files.lines( path ).toList(); } catch ( IOException e ) { e.printStackTrace(); }

我们可以使用 Files.readAllLines 进一步缩短它。

List < String > lines = List.of();
try { lines = Files.readAllLines( path ); } catch ( IOException e ) { e.printStackTrace(); }

使用List.copyOf to make an unmodifiable list,确保不对列表内容进行任何更改。

List < String > lines = List.of();
try { lines = List.copyOf( Files.readAllLines( path ) ); } catch ( IOException e ) { e.printStackTrace(); }

lines.toString() = [Alice engineer, Bob cook, Carol pilot, Darren astronaut, Edith dancer, Frank poet]

对于每一行,获取一个单词列表。

for ( String line : lines )
{
    List < String > words = List.of( line.split( " " ) );  // Pass `split` method’s returned array of strings to `List.of` to get an unmodifiable list of the words.
    System.out.println( words.size() + " words in: " + words );
}

将所有代码放在一起。

File file = new File( "/Users/basilbourque/names.txt" );
Path path = file.toPath();

List < String > lines = List.of(); // Default to empty list.
try { lines = List.copyOf( Files.readAllLines( path ) ); } catch ( IOException e ) { e.printStackTrace(); }
System.out.println( "lines = " + lines );

for ( String line : lines )
{
    List < String > words = List.of( line.split( " " ) );  // Pass `split` method’s returned array of strings to `List.of` to get an unmodifiable list of the words.
    System.out.println( words.size() + " words in: " + words );
}

当运行.

lines = [Alice engineer, Bob cook, Carol pilot, Darren astronaut, Edith dancer, Frank poet]
2 words in: [Alice, engineer]
2 words in: [Bob, cook]
2 words in: [Carol, pilot]
2 words in: [Darren, astronaut]
2 words in: [Edith, dancer]
2 words in: [Frank, poet]