在 Java 中从文件中读取 words/phrases,区分并写入另一个文件

Read words/phrases from a file, make distinct, and write out to another file, in Java

我有一个文本文件,每行都有一个单词或短语。我如何:

Whosebug 有其他语言(例如 C, PHP, Python, Prolog, and VB6)对类似问题的回答。但是我找不到 Java.

以下 Java 8 示例代码应该有所帮助。它既不健壮也没有经过充分测试。并且它假定您的所有数据都可以轻松地放入内存中。虽然不完美,但这个例子应该能让你朝着正确的方向前进。

Java Collections Framework (Tutorial) defines the Set interface for collecting a distinct bunch of values. As an implementation of that interface, we will use HashSet.

请注意,我们试图从每一行中 trim 任何白色 space。不幸的是,String::trim 方法并没有彻底解决这个问题。在实际工作中,我会用对 trimming 的更好库的调用替换该调用,例如 Google Guava。您可能想要删除 所有 个非打印字符。

我们使用 isEmpty 方法测试每个字符串,以过滤掉没有任何字符的字符串。

以下代码使用 Try-With-Resources syntax 自动关闭任何打开的文件。

// Read file.
// For each line, trim string. 
// Add to Set to make collection of distinct values.
// Convert to List, and sort.
// Write back values to text file.

Set< String > set = new HashSet<>( );

String path = "/Users/yourUser/yourInputFile.txt";
File file = new File( path );
try ( BufferedReader br = new BufferedReader( new FileReader( file ) ) ) {
    String line;
    while ( ( line = br.readLine( ) ) != null ) {
        // Process the line.
        String keyword = line.trim( );
        if ( ! keyword.isEmpty( ) ) {  // If keyword is not empty, collect it.
            set.add( keyword );
        }
    }
} catch ( IOException e ) {
    e.printStackTrace( );
}

现在我们有 Set of distinct values. To sort them, we need to convert to a List. The Collections class (notice the "s") offers a static method for sorting a List of items that implement Comparable.

List< String > keywords = new ArrayList< String >( set );
Collections.sort( keywords );

让我们将排序后的列表写入存储中的文件。

// Write to file. 
// Use Try-With-Resources to automatically close the file if opened.
try ( 
        FileWriter writer = new FileWriter( "/Users/yourUser/yourOutputFile.txt" ) ;
) {
    for ( String k : keywords ) {
        writer.write( k + "\n" );  // You may want a different newline instead of the Unix-style LINE FEED hard-coded here with "\n".
    }
} catch ( IOException e ) {
    e.printStackTrace( );
}

如果需要,请在控制台上查看结果。

System.out.println( "Size: " + keywords.size( ) );
System.out.println( "keywords: " + keywords );
System.out.println( "Done." );

您可以利用:

……优雅的解决问题:

public static void main(String... args) {
  Path input = Paths.get("/Users/yourUser/yourInputFile.txt");
  Path output = Paths.get("/Users/yourUser/yourOutputFile.txt");

  try {
   List<String> words = getDistinctSortedWords(input);
   Files.write(output, words, UTF_8);
  } catch (IOException e) {
    //log error and/or warn user
  }
}

private static List<String> getDistinctSortedWords(Path path) throws IOException {
  try(Stream<String> lines = Files.lines(path, UTF_8)) {
    return lines.map(String::trim)
            .filter(s -> !s.isEmpty()) // If keyword is not empty, collect it.
            .distinct()
            .sorted()
            .collect(toList());
  }
}

注意:需要静态导入

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.toList;