Search code examples
javaexceptionarraylistprintwriter

Using PrinterWriter with a String ArrayList


Here is the prompt I was given to work with (I got the expected result by replacing the line "File input = new File(args[0]);" with "File input = new File("data.txt");" but I was wondering if this could be done somehow using a command line): The following program has the String array-list object. Compute the total value from the input file, after that print out the total value into a new file.

import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class FileIOArrayList {
 public static void main(String[] args) throws FileNotFoundException
 {

 List<Integer> data = new ArrayList<Integer>();

File input = new File(args[0]);
 Scanner myScanner = new Scanner(input);
 while (myScanner.hasNextInt()){
      data.add(myScanner.nextInt());
      }

      PrintWriter myWriter = new PrintWriter("output.txt");

       for(int i=0; i<data.size(); i++)
      {
      myWriter.println(data.get(i));
      }
      myWriter.close();

    }
   }

====Output Example=======

32
54
76
90
10
300
543
179
4
2
5
Total sum = 1295

Solution

  • If you want to do this through the command line, you must specify command-line arguments. You can pass in the name of the file as a command-line argument by placing it after the class name like so:

    java FileIOArrayList data.txt
    

    Check out the tutorial on Command Line Arguments.