Command Line Arguments

So far we have been taking input during runtime. Command line arguments let us take input from the user right before runtime.

Everything that comes after the program name is a command line argument.

java MyProgram argument1 argument2 argument3

Your program can take as many command line arguments as you wish.

Recall:

public static final void main(String[] args)

The highlighted code represents a String Array. This String Array holds the command line arguments you passed to your program.

args[0]; // "argument1"
args[1]; // "argument2"
args[2]; // "argument3"

Reading from a File

Now that we know how to give our program command line arguments, lets use this to pass a file name to our program.

java MyReader test.txt

We have been using Scanner to read in user input. We can also use the Scanner to read this file we passed in.
Here is what we have been doing:

Scanner s = new Scanner(System.in);

In order to read the file we need to pass the Scanner a file. If you look at the Scanner class in the Java API, you will see that it has multiple constructers. Now it is time to use the constructor that takes in a File object.
We create a File object:

//Using command line arguments
File inputFile = new File(args[0]); 

or

File inputFile = new File("test.txt");



And pass that into the constructor of the Scanner object as an explicit parameter.

Scanner in = new Scanner(inputFile);

Now we are all set to start reading in the file. To do this we will use two methods of the Scanner Class:

hasNextLine()
nextLine()

hasNextLine()returns a boolean. It will return true if there is another line to read from your input source. It will return false when it reaches the end of your input stream. When the Scanner object reaches the end of a file hesNextLine() will return false.

nextLine()returns a String. This method returns the input line by line. The Scanner starts from where it last returned and reads until it reaches a new line character(\n).

Writing to a File

Writing to a file requires another object than Scanner. There are multiple options to chose from, we will cover PrintWriter.
The PrintWriter constructor expects a file name or a File object.

//Here outputFile could either be a String or a File.
PrintWriter writer = new PrintWriter(outputFile);

Writing to a File is as simple as printing to your console. Remember: System.out.println()

//Now our file has "Hello"
writer.println("Hello");

Here is an example of reading from one file and writing what you have read to another file:

while(in.hasNextLine()) {
	writer.println(in.nextLine());
}

Once we are done with writing to a File we need to close() the File. If you do not close() a File the behavior is undefined, meaning that when you go back and try to read from the file you have just written to, you might see a properly formatted file or you might see something that doesn't make any sense.

writer.close();

Keep in mind that after you close a File you cannot write to it.

Strings

String s = "Hello World";


subtring()

for(int i=0; i < (s.length()-1); i++){

	System.out.println(s.substring(i,i+1));

}

This will print:
H
e
l
l
o

W
o
r
l
d

Don't forget that white space characters count as proper characters.

charAt()

s.charAt(0); // H
s.charAt(5); // " " Space character

It is important to note that charAt() returns a char.

equals() and equalsIgnoreCase()

String s = "Hello World";
String e = "hello world";

Since we can't use == to compare objects, we need equals() to determine whether two Strings are equal.

if(s == "Hello World"){
	//Will not go in here. The if statement will not evaluate to true.
}
if(s.equals("Hello World"){
	System.out.println("Yay you made it!");
}
if(s.equalsToIgnoreCase(e)){
	System.out.println("This is not case sensitive");
}

concat()

String newS = s.concat(", I'm Zeynep");
System.out.println(newS); 	//Prints 	Hello World, I'm Zeynep

replace()

String newS = s.replace('e','a');
System.out.println(newS); 	//Prints 	Hallo World

newS = s.replace('l','a');
System.out.println(newS); 	//Prints 	Heaao Worad

replace() replaces all instances of the seeked character.

toLowerCase()

String newS = s.toLowerCase();
System.out.println(newS); //Prints 	hello world

toUpperCase()

String newS = s.toUpperCase();
System.out.println(newS); //Prints 	HELLO WORLD

indexOf()

You can give it a char

int index = s.indexOf('o');
System.out.println(index);  // Prints	4

Or you can give it a String

index = s.indexOf("o");
System.out.println(index);  // Prints	4

split()

String[] a = s.split(" ");
System.out.println(a[0]); // Prints	Hello
System.out.println(a[1]); // Prints 	World
 
a = s.split("e");
System.out.println(a[0]); // Prints	H
System.out.println(a[1]); // Prints 	llo World

Note that the character you searched for is missing from the returned Strings.


MyReader.java

We will go over this code in this recitation.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class MyReader {

	public static final void main(String[] args) {
        
		System.out.println("File name: " + args[0]);

		File inputFile = new File(args[0]);
        
        	Scanner s = new Scanner(System.in);
		System.out.print("output file name: ");
		String outputFile = s.nextLine();
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(outputFile);
		} 
		catch(FileNotFoundException e) {
			System.out.println("Writer Failed.");
			System.exit(1);
		}

		Scanner in = null;
		try {
			in = new Scanner(inputFile);
			System.out.println("We made it!");
		} 
		catch( FileNotFoundException e) {
			System.out.println("The file doesn't exist.");
			System.exit(1);
		}

		while(in.hasNextLine() ) {
			writer.println(in.nextLine() );
		}
		writer.close();
	}
}