世界震撼.dev

いつか世界を驚かせるためのメモ

テキストファイルの重複要素を削除するクラスを書いてみた

引数1に入力元、引数2に出力先のパスを指定する

HashSetにそのままaddすると順序が保持されないなんて初耳だった

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.LinkedHashSet;

class Distinct{

    public static void main( String...args ){
        if( args.length != 2 ){
            System.out.println( "argument error" );
            System.out.println( "argument1 : readfilepath , argument2 : writefilepath" );
            return;
        }
        if( args[ 0 ].equals( args[ 1 ] ) ){
            return;
        }
        File readfile = new File( args[ 0 ] );
        File newfile = new File( args[ 1 ] );
        try(BufferedReader br = Files.newBufferedReader( readfile.toPath( ) , StandardCharsets.UTF_8 );
            BufferedWriter bw = Files.newBufferedWriter( newfile.toPath( ) , StandardCharsets.UTF_8 , StandardOpenOption.WRITE , StandardOpenOption.CREATE_NEW ); ){
            HashSet< String > distinct = new LinkedHashSet< String >( 5000 );
            for( String line; ( line = br.readLine( ) ) != null; ){
                distinct.add( line );
            }
            for( String line : distinct ){
                bw.write( line + "\n" );
            }
        }catch( IOException e ){
            e.printStackTrace( );
        }
    }
}