0

I'm trying to figure out how to pass two files (input.txt and output.txt) as arguments to my main method, read the input file, pass it to a recursive method, then write the mutated string to an output file. I've never worked with commandline arguments before, so I'm not sure how to go about making it work. Here's the code so far:

public static void main(String[] args)  
{ 
    ArrayList<String> fileInput = new ArrayList<String>();//ArrayList to hold data from input file
    File file = new File(args[0]);
  try
  {

        Scanner scan = new Scanner(new File(args[0]));
        FileInputStream readFile = new FileInputStream("input.txt"); // readFile passed from args[0]; args[0] is the argument passed as a string that is held at the 0 index of the args array 
        fileInput.add(file); //red error line under Add
  }
  catch(IOException e)
  {
    e.printStackTrace();
    System.exit(0);
  }

  ArrayList<String> strArray = new ArrayList<String>(); 
  String s;

  for(int i = 0; i < file.length() ; i++) //int i = 0; length of stored string data object; i++)
  {
      //recursiveMarkUp is a string type
        strArray.add(file.recursiveMarkUp());//call the markup method and save to an array so we can print to the output file later 
        //line to print output to output.txt
  }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

0

When you pass in arguments, they are stored in the args[] array and are accessed like any normal array within main.

File input = new File(args[0]);
File output = new File(args[1]); // make sure you check array bounds

Your comment pointing out the red error line occurs because you are trying to add a File object to an ArrayList<String> which are incompatible. However there's no need to do this step anyway.

You can construct the output stream with the file above:

output.createNewFile(); // create the file so that it exists before writing output
FileOutputStream outStream = new FileOutputStream(output);
OutputStreamWriter outWriter = new OutputStreamWriter(outStream);

If you're using Java 8+, using Files.lines() you can process every line of the file as a stream of Strings

Files.lines(input.toPath())
    .map(line -> recursiveMarkup(line))
    .forEach(markedUp -> outWriter.write(markedUp));

To do this without streams:

BufferedReader reader = new BufferedReader(new FileReader(input));
String line = "";
while(line != null) {
    line = recursiveMarkup(reader.readLine());
    outWriter.write(line);
}

I've excluded try/catch blocks for brevity. I've also assumed that you do actually want to process the input file one line at a time; if that's not the case, adjust as necessary. You should also consider explicitly defining file encodings (UTF-8, etc.) when reading/writing data, though here I've also left it out for brevity.

NAMS
  • 983
  • 7
  • 17