Archive

Posts Tagged ‘Java’

Spinning command line cursor in Java

January 29th, 2010 Nick No comments

As a follow-up to my previous article on displaying a spinning cursor to display program activity, I have created a more useful example that could be adapted for use.

The original problem was this – I was writing a program that performed a particular task and I needed some way of showing the program was alive and functioning correctly whilst doing the task.

In Windows this is done by changing the mouse cursor into an hourglass, unfortunately on the command line we don’t have such GUI luxuries. One classic option is to create a spinning line by displaying | / – \ and so on.

The example below creates two child threads; one to do a particular job (in this case slowly count to 10) and another thread to display a spinning cursor.

/**
 * Spinning cursor test class
 *
 * @author Nick Giles
 */
public class SpinTest
{
    /**
     * Thread which does the stuff we're interested in
     *
     */
    private Thread stuff;

    /**
     * Thread class which does stuff in the background
     *
     */
    private class Stuff implements Runnable
    {
        public void run()
        {
            int result = 0;

            try
            {
                // Slowly count to 10, although you can of course put whatever
                // you want here, presumably something a bit more useful
                while (result < 10)
                {
                    result++;
                    Thread.sleep(1000);
                }
            }
            catch (InterruptedException e)
            {
                // If interrupted then quietly end the thread, you may well
                // want to handle this in some way
            }
        }
    }

    /**
     * Spinner thread
     *
     */
    private class Spinner implements Runnable
    {
        public void run()
        {
            String[] phases = {"|", "/", "-", "\\"};

            try
            {
                while (true)
                {
                    for (String phase : phases)
                    {
                        System.out.printf("\b"+phase);

                        Thread.sleep(100);
                    }
                }
            }
            catch (InterruptedException e)
            {
                // No need to do anything if interrupted
            }
        }
    }

    /**
     * Handles all shutdown functions
     *
     */
    public class ShutdownHandler extends Thread
    {
        public void run()
        {
            // On interrupt, stop doing stuff
            stuff.interrupt();
        }
    }

    public void doStuff()
    {
        try
        {
            // Attach an object to handle shutdown signals (i.e. ctrl+c)
            Runtime.getRuntime().addShutdownHook(new ShutdownHandler()); 

            // Create a new thread for spinning the cursor
            Thread spinner = new Thread(new Spinner());

            // Create a new thread for doing stuff
            this.stuff = new Thread(new Stuff());

            // Nice message to user
            System.out.printf("Doing stuff...  ");

            // Start doing stuff
            this.stuff.start();

            // Start spinning the cursor
            spinner.start();

            // Check the thread doing stuff is still doing stuff
            while (stuff.isAlive())
            {
                stuff.join(1000);
            }

            System.out.printf("\bDone.\n");

            // The thread doing stuff has finished, so stop spinning
            spinner.interrupt();

            // Wait for the spinning thread to terminate
            spinner.join();

            System.out.println("The End.");
        }
        catch (InterruptedException e)
        {
            System.out.println("Interrupted");
        }
    }

    /**
     * Main method
     *
     */
    public static void main(String[] args)
    {
        SpinTest test = new SpinTest();

        test.doStuff();
    }
}

It’s a fairly basic implementation but it should be fairly simple to extend it for a real-world application.

Spinning command line cursor in Java and PHP

January 29th, 2010 Nick No comments

Update: I have created an updated article which describes a multithreaded approach in Java Spinning command line cursor in Java

I think I must be really bored this morning, I can’t believe I’m actually blogging this, but it might be useful for someone, who knows.   Anyway, I am currently writing a program that sits and does stuff for a very long time, and I need a way to nicely indicate the program is still running and doing its stuff.   So I have created a little method that prints a spinning cursor on the command line.   The implementation would of course have to be multithreaded; one thread to do stuff, the other to spin the cursor – if there’s time I’ll update it to a more complete solution, but for now here’s the spin implementation:


public class Spin
{
    public static void main(String[] args) throws InterruptedException
    {
        String[] phases = {"|", "/", "-", "\\"};

        System.out.printf("Spinning... |");

        while (true)
        {
            for (String phase : phases)
            {
                System.out.printf("\b"+phase);
                Thread.sleep(100);
            }
        }
    }
}

And here it is in PHP.

<?php

    $phases = array("|", "/", "-", "\\");

    printf("Spinning... |");

    while (1)
    {
        foreach ($phases AS $phase)
        {
            printf('%s%s', chr(8), $phase);
            usleep(100000); // Replace this with one iteration of doing stuff
        }
    }

Of course PHP doesn’t support threading so you’d have to call each iteration of the “doing stuff” loop inside the spin loop which would mean you’d get a bit of a jumpy spinning cursor but I think most people could live with that.

Categories: Java, PHP Tags: , , , , ,

Syntax error, parameterized types are only available if source level is 1.5

December 19th, 2009 Nick 1 comment

I recently installed Eclipse and all of a sudden my Java applications failed to build with the error:

Syntax error, parameterized types are only available if source level is 1.5

After a bit of Googling I figured out that Eclipse installed a different JVM and set it as the default one.   On Ubuntu (at least) the way to change the default JVM is by typing this into the console:

sudo update-alternatives --config java

It will show you which JVM is currently selected and allow you to choose a different one as default.

Categories: Java Tags: , , , , , ,

Java: touch – set file last modified time

December 11th, 2009 Nick No comments

I just discovered that I need to touch() a file in Java. It appears there isn’t a way to do this using the standard Java library, so I rolled my own:

import java.io.*;
import java.util.Date;

class Touch
{
    /**
     * Touches a given file
     *
     * @author Nick Giles <http://www/4pmp.com/>
     */
    public static void main(String args[])
    {
        try
        {
            // Create a new file object for the file we want to touch
            File f = new File("touch.txt");

            // See if the file already exists
            if (f.exists())
            {
                // The file already exists, so just update its last modified time
                if (!f.setLastModified(System.currentTimeMillis()))
                {
                    throw new IOException("Could not touch file");
                }
            }
            else
            {
                // The file doesn't exist, so create it
                f.createNewFile();
            }
        }
        catch (SecurityException e)
        {
            System.err.println("Security Error: " + e.getMessage());
        }
        catch (IOException e)
        {
            System.err.println("IO Error: " + e.getMessage());
        }
    }
}

Just like the Linux command, if the input is a directory then it will update the last modified time for the directory but not recurse into it. If you need to recurse then the above can easily be extended to recurse itself using f.isDirectory() and f.listFiles(). If anyone needs this then just let me know and I’ll rustle it up, but for now I’ll leave that as en exercise for the reader :-)

Categories: Java Tags: , , , ,