In: Computer Science
Make a program to read a file, filled with words separated by new lines, from command line arguments (args[0]), print the file, and then add each word into an arraylist.
After making the arraylist, iterate through it and print its contents.
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class PrintFileWords { public static void main(String[] args) { if (args.length > 0) { Scanner in = new Scanner(System.in); File file = new File(args[0]); try { Scanner fin = new Scanner(file); System.out.println("sample file: " + args[0]); ArrayList<String> list = new ArrayList<>(); while (fin.hasNext()) { list.add(fin.nextLine()); } for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } fin.close(); } catch (FileNotFoundException e) { System.out.println(file.getAbsolutePath() + " is not found!"); } in.close(); } else { System.out.println("Please provide file name as command line argument"); } } }