Search code examples
javafileargs

JAVA Importing files via ARGS


I need to import files for input and output by ARGS. This code seems to be too long, can it be more minimalist ?

import java.io.File;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println(args[0]);

        for (int i = 0; i < args.length; i++) {

            File f = new File(args[i]);
            if (f.exists()) {
                System.out.println("file " + args[i] + " exits.");
            } else {
                System.out.println("file " + args[i] + " does not exist");
                System.exit(0);
            }
        }

    }

}

Solution

  • Using Java 8 streams, your code can be rewritten as:

    import java.io.File;
    import java.util.Arrays;
    
    public class Main {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            System.out.println(args[0]);
    
            Arrays.asList(args).stream().map((s) -> new File(s)).forEach((f) -> {
                if (f.exists()) {
                    System.out.println("file " + f + " exits.");
                } else {
                    System.out.println("file " + f + " does not exist");
                    System.exit(0);
                }
            });
        }
    
    }
    

    I don't think your focus should be on LOC rather it should be on how well your code is structured and written :)