Column Switcher

Yesterday I met a problem where I needed to replace the columns of a csv-file separated by whitespace, since this was some pretty basic stuff I wrote a simple program in Java fairly easily.

Today when I woke up I thought that maybe I should try and see how I could do the same with Shell Scripting, so here goes (the programs are available at my github here):

import java.util.Scanner;
import java.io.*;

public class Cols {

    /**
     * This program takes a csv file separated by whitespace and replaces the first with the second column.
     * @name Cols
     * @author tcarisland
     * @date 6.sep.2017
     */

    public static void main(String args[]) {
	try {
	    Scanner in = new Scanner(new File(args[0]));
	    PrintWriter out = new PrintWriter(new File(args[1]));
	    while(in.hasNextLine()) {
		String cols[] = in.nextLine().split("\\s+");
		if(cols.length > 1)
		    out.println(cols[1] + " " + cols[0]);
	    }
	    in.close();
	    out.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

}

 

And the Bash program:

 

#/bin/bash

#A minimal version of the cols program to do exactly the same as the java program.
#Needs two arguments.

rm -f $2 && touch $2;

while IFS=" " read c1 c2
do
    echo $c2" "$c1 >>$2;
done < $1

HashMapMaker

While working on a problem today I found I wanted to simplify the process of creating predefined HashMaps.

So I made this little utility program to take two files and create a HashMap<String, String> from such a file.

Nothing much, but I put it up on my GitHub here nonetheless.

import java.util.Scanner;
import java.io.*;

public class HashMapMaker {

    /**
     * A simple program that creates a HashMap from a file with fields separated by whitespace.
     * @name HashMapMaker
     * @author tcarisland
     * @date 5.sep.2017
     */
    
    public static void main(String args[]) {
	try {
	    Scanner in = new Scanner(new File(args[0]));
	    PrintWriter out = new PrintWriter(new File(args[1]));
	    out.println("private static final Map<String, String> m = new HashMap<String, String>() {{");
	    while(in.hasNextLine()) {
		String pair[] = in.nextLine().split("\\s+");
		if(pair.length > 1)
		    out.println("put (\"" + pair[0] + "\", \"" + pair[1] + "\");");
	    }
	    in.close();
	    out.println("}};");
	    out.close();
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
    
}