Category: Java


The tutorial below will show any Java user how they can read the size of a file in bytes and convert it into the most appropriate format (i.e. kilobytes and megabytes) in order to display the size to the user in a simple format.

This tutorial shows how to open a file based on the value that you give the filenameString variable, read its size in bytes and if necessary, convert the value to a kilobytes or megabytes value and finally display the value to the user. The code to do so is highlighted below and comes in two forms: commented and uncommented as to improve readability:

Commented code:

package getfilesize;

/*
* Title:       GetFileSize
* Version:     1.0.0
* Date:        20/01/2012
* Description: Displays the size of a file, who’s path is defined by the value of filenameString.
* Author:      Dillon Chaffey
* Website:     https://chafflube.wordpress.com
* E-mail:      chafflube@hotmail.com
*/

import java.io.*;

public class GetFileSize {

    // Create some static variables to be used within the main method below
    static String filenameString;
    static File file;
    static long fileSizeBytesLong;
   
    public static void main(String[] args) {
        // Assign a value to the the filenameString variable below. This value must be the absolute path to the file the user wishes to open
        filenameString = "<path to file goes here>";
       
        try {
            // Try to open a new file using the value of the filenameString variable as the file path           
            file = new File(filenameString);
        }
        // If something goes wrong when trying to open the file display some information to the user about what went wrong
        catch (Exception e) {
            e.printStackTrace();
        }
       
        // Make the value of the fileSizeBytesLong variable equal to the amount of bytes within the opened file using file.length()
        fileSizeBytesLong = file.length();
       
        // Check whether the file is less than 1024 bytes and inform the user of the size in bytes, else inform the user of the size in KB, or MB
        if (file.length() < 1024) {
            System.out.println("The size of the file at: \"" + filenameString + "\" is: " + fileSizeBytesLong + "bytes.");
        }
        if (file.length() >= 1024 && file.length() < 1048576) {
            System.out.println("The size of the file at: \"" + filenameString + "\" is: " + (fileSizeBytesLong / 1024) + "kilobytes.");
        }
        if (file.length() >= 1048576 && file.length() < 1073741824) {
            System.out.println("The size of the file at: \"" + filenameString + "\" is: " + ((fileSizeBytesLong / 1024) / 1024) + "megabytes.");
        }

        // Close the program
        System.exit(0);
    }
}

Uncommented code:

package getfilesize;

/*
* Title:       GetFileSize
* Version:     1.0.0
* Date:        20/01/2012
* Description: Displays the size of a file, who’s path is defined by the value of filenameString.
* Author:      Dillon Chaffey
* Website:     https://chafflube.wordpress.com
* E-mail:      chafflube@hotmail.com
*/

import java.io.*;

public class GetFileSize {

    static String filenameString;
    static File file;
    static long fileSizeBytesLong;
   
    public static void main(String[] args) {
        filenameString = "<path to file goes here>";
       
        try {
            file = new File(filenameString);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
       
        fileSizeBytesLong = file.length();
       
        if (file.length() < 1024) {
            System.out.println("The size of the file at: \"" + filenameString + "\" is: " + fileSizeBytesLong + "bytes.");
        }
        if (file.length() >= 1024 && file.length() < 1048576) {
            System.out.println("The size of the file at: \"" + filenameString + "\" is: " + (fileSizeBytesLong / 1024) + "kilobytes.");
        }
        if (file.length() >= 1048576 && file.length() < 1073741824) {
            System.out.println("The size of the file at: \"" + filenameString + "\" is: " + ((fileSizeBytesLong / 1024) / 1024) + "megabytes.");
        }

        System.exit(0);
    }
}

Also, note that the above code will not execute without errors until the value of the filenameString has been edited to reflect the absolute file path of an existing file.

Hopefully this tutorial has allowed you to gain a better understanding of the workings of the Java programming language. Good luck with your current and future Java projects.

This tutorial will show any Java developer (beginner or otherwise) how to generate a random number within an arbitrary range. You can use random numbers for many purposes, such as; artificial intelligence, game design and mathematical applications.

The code to create a simple random number generator that will continue to produce random numbers within an arbitrary range until the program is closed is below:

package randomnumbercreator;

/*
* Title: Random Number Creator
* @author Dillon Chaffey
* Website: https://chafflube.wordpress.com
* E-mail: chafflube@hotmail.com
*/

public class RandomNumberCreator {
    // Variable declarations
    static int randomNumberInt;
    static int maxRangeInt;
    static int minRangeInt;
   
    public static void main(String[] args) {
        minRangeInt = 0;    // This creates the base of the range
        maxRangeInt = 100;  // This creates the top of the range
       
        // Create infinite loop
        while(true) {
            // Update the value of randomNumberInt
            randomNumberInt = (minRangeInt + (int)(Math.random() * (maxRangeInt – minRangeInt)));
            // Print the updated value of randomNumberInt
            System.out.println(randomNumberInt);
        }
    }
}

The above code, if compiled “as is,” will provide you with an endless stream of random numbers within the range of 0 to 100. However, you can easily change this range by changing the value of minRangeInt to the lower end of the range you desire and changing the value of maxRangeInt to the higher end of the range you desire.

I hope that by teaching you how to generate random numbers within a range I can save you the time that I took to learn how to do so. Good luck with your future Java coding ventures!

This tutorial will describe how you can use a single line of code to make a JTextArea scroll down to the bottom of the text area automatically as text is appended to it. This is excellent for applications such as; network clients and servers that must display massive amounts of text data as well as any application that requires adding data to a log that is visible at all times.

In this example the JTextArea will be referred to as “TextArea.” The magic line of code is highlighted below:

TextArea.setCaretPosition(TextArea.getText().length() – 1);

All you need to do now is add this line below every TextArea.append(); command. An example is below:

TextArea.append(textString);

TextArea.setCaretPosition(TextArea.getText().length() – 1);

The setCaretPosition() method can be used when using the setText() method on a JTextArea also. There may also be further uses for the setCaretPosition() method, however, I have not yet needed them, but if you find them, well done!

This is a very common question and it just made sense to give it a quick and simple answer. Hopefully this has solved your problem. Good luck with your program!

This tutorial will provide you with a detailed understanding of how a TCP client is built using Java. Also, several of the concepts of Java clients will be explained.

In order to build a TCP client in Java the basics of Java must first be learned. This can be done by reading a Java book aimed at beginners. I have several recommendations for such literature in order from 1 to 3, 1 being my personal favourite and 3 being my least favourite, including:

  1. Java For Dummies (http://www.amazon.com/Java-Dummies-Aaron-Walsh/dp/156884641X)
  2. Java All In One Desk Reference For Dummies (http://www.amazon.com/Java-All-One-Reference-Dummies/dp/076458961X)
  3. Beginning Programming  with Java For Dummies (http://www.amazon.com/Beginning-Programming-Java-Dummies-Barry/dp/0764588745)

 

The above list of books is current at the time of writing. However, I take no responsibility for the availability of these books in the future.

 

Below is the source code for the most recent revision of the first Java client I ever wrote. So it is very unlikely that there will be any bugs.

package client;

/*
* @author Dillon Chaffey
* Website: https://chafflube.wordpress.com
* E-mail: chafflube@hotmail.com
*/

import java.io.*;
import java.net.*;

public class Client {
    static String hostString = "127.0.0.1";     // Modify this value (127.0.0.1) to the IP address you want your client to connect to (the server’s IP address)
    static int portInt = 45454;                            // Modify this value (45454) to the port number that the server is accepting connections on
    static Socket connectionSocket = null;
    static PrintWriter out = null;
    static BufferedReader in = null;
    static String fromUserString = null;
    static String fromServer = null;
    static BufferedReader stdIn = null;
    static String hostInetAddressString = null;  

    public static void main(String[] args) {
        try {
            connectionSocket = new Socket(hostString, portInt);
            hostString = connectionSocket.getInetAddress().toString();
            out = new PrintWriter(connectionSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            // Get the Inet Address of the connectionSocket and store it in the hostInetAddress InetAddress variable and then cast the hostInetAddress to a String named hostInetAddressString
            hostInetAddressString = connectionSocket.getInetAddress().toString();
            System.out.println("Connected to server with Inet Address " + hostInetAddressString + " on port: " + connectionSocket.getPort() + "\n");
        }
        catch (Exception e) {
            System.err.println(e);
            System.exit(1);
        }
       

        // This is used to allow the client to receive input based on the program’s user pressing keys on their keyboard
        stdIn = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            try {
                if (fromUserString != null) {
                    out.println(fromUserString);
                    fromUserString = null;
                }   
            }
            catch (Exception e) {
                System.err.println(e);
                break;
            }
        }
    }
   
    public void closeClient() {
        // Try to close printers, writers and then sockets if it fails catch an exception
        try {
            out.close();
            in.close();
            stdIn.close();
            connectionSocket.close();
        }
        catch (Exception e) {
            System.err.println(e);
        }       
    }
}

 

The above code may be hard to read due to the fact that it is so heavily commented. The reason that it is commented so heavily is so that beginner users of Java are able to more easily gain an understanding of the code. If the code does not make any sense whatsoever then it is more than likely within your best interests to read one of the aforementioned beginner Java books and experiment with the code within the books and rework them to suit real life situations, as by doing so you are bound to learn faster than simply reading the books and neglecting to practice writing actual code. A good thing to do is write a program in “pseudo-code,” which is writing a program in English rather than actual code and it should give an overall view of the program you wish to create. After you have done this you may then learn how to code your program one piece at a time. Eventually you will have a functional, useful program and you will have learned more about the Java programming language than simply reading a book.

 

Now that you have built your own client you will need a server in order to experiment with network communication. Fortunately there is a tutorial on this site that shows you exactly how you can do this. The link to this tutorial is below:

https://chafflube.wordpress.com/2012/01/16/how-to-build-a-tcp-server-in-java/

I hope that this tutorial has helped you on your journey to learning the Java programming language. Java is arguably the best platform for network software development. So by creating clients and servers in Java you are making a very efficient use of such a fast-moving, powerful language.

This tutorial will provide you with a detailed understanding of how a TCP server is built using Java. Also, several of the concepts of Java servers will be explained.

In order to build a TCP server in Java the basics of Java must first be learned. This can be done by reading a Java book aimed at beginners. I have several recommendations for such literature in order from 1 to 3, 1 being my personal favourite and 3 being my least favourite, including:

    1. Java For Dummies (http://www.amazon.com/Java-Dummies-Aaron-Walsh/dp/156884641X)
    2. Java All In One Desk Reference For Dummies (http://www.amazon.com/Java-All-One-Reference-Dummies/dp/076458961X)
    3. Beginning Programming  with Java For Dummies (http://www.amazon.com/Beginning-Programming-Java-Dummies-Barry/dp/0764588745)

 

The above list of books is current at the time of writing. However, I take no responsibility for the availability of these books in the future. Although, these books are of such high quality for the Java beginner that I believe anybody would find great difficulty in discontinuing them.

 

Below is the source code for one of the first TCP servers I have built in Java. Don’t be fooled by the fact that it was one of the first I built as since I have built it I have used it as a base for many of my programs requiring a reliable TCP network connection and this code is the most recent at the time of writing of my revisions.

package server;

import java.net.*;
import java.io.*;

public class Server { 
    // Below are variable declarations. They are given the static modifier as they need to be used within a static context (the main() method)
    static String hostInetAddressString;
    static String clientInetAddressString;
    static int clientPortInt;
    static ServerSocket serverSocket = null;
    static Socket clientSocket = null;
    static int clientSocketReceiveBufferSizeInt;
    static int clientSocketSendBufferSizeInt;
    static BufferedReader stdIn;
    static String fromUserString;
    static PrintWriter out;
    static BufferedReader in;
    static int portInt;
    static String fromClient;
   
    // The main() method of the server program (body of the program)
    public static void main (String[] args) {
        portInt = 45454; // Change this value to determine which port the server will start one and can be accessed through using a client
        // These two variables are used to set the receive and send buffer size of the clientSocket when a client connects
        // A lower value (2-4) will generally increase the performance of a connection frequently transferring small amounts of data (i.e. short text strings)
        // A higher value (4-16) will generally increase the performance of a connection frequently transferring large amounts of data (i.e. file transfer)
        clientSocketReceiveBufferSizeInt = 2;
        clientSocketSendBufferSizeInt = 2;
        // Alert server user that the server is initiating
        System.out.println("Server is intitiating. Please wait…");

        try {
            serverSocket = new ServerSocket(portInt);
            hostInetAddressString = serverSocket.getInetAddress().toString();
        }
        catch (IOException e) {
            System.out.println("Could not listen on port: " + portInt);
            System.exit(1);
        }
            // Alert server user that the server is now ready to accept incoming connection requests
            System.out.println("Server initiated. Awaiting connection request…\n");

        try {
            clientSocket = serverSocket.accept();
            // Get the Inet Address of the clientSocket and store it in the clientInetAddress InetAddress variable and then cast the clientInetAddress variable to a String named clientInetAddressString
            clientInetAddressString = clientSocket.getInetAddress().toString();
            // Set the receive buffer size of the clientSocket to that set in the int variable clientSocketReceiveBufferSizeInt
            clientSocket.setReceiveBufferSize(clientSocketReceiveBufferSizeInt);
            // Set the send buffer size of the clientSocket to that set in the int variable clientSocketSendBufferSizeInt
            clientSocket.setSendBufferSize(clientSocketSendBufferSizeInt);
            // Alert the server user that they are connected to the server and give them some details of the connection
            System.out.println("Client connected with Inet Address " + clientInetAddressString + " on port: " + clientSocket.getPort() + "\n");
        }
        catch (IOException e) {
            System.err.println(e);
            System.exit(1);
        }

        try {
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        }
        catch (Exception e) {
            System.err.println(e);
        }

        while (true) {
            try {
                if ((fromClient = in.readLine()) != null) {
                    System.out.println("Client: " + fromClient + "\n");   
                }
                else {
                    //break;
                }
            }
            catch (IOException ioe) {
                System.err.println(ioe);
                closeServer();
            }
        }
    }
   
    public static void closeServer() {
        // Close writers, readers and then sockets
        try {
            out.close();
            in.close();
            clientSocket.close();
            serverSocket.close();
            System.exit(0);
        }
        catch (Exception e) {
            System.err.println(e);
        }
    }
}

 

The above code is commented as to allow a Java programmer who has read one or more of the aforementioned books to understand the code at least partially if not fully. However, if you have not yet invested the time to read one of those books, the code will probably not make much sense. Although even if you have not yet read any of the books, you have no reason to be concerned as the Java For Dummies book can be read through in just a few hours a day for 2-4 days and that is for an average speed reader (such as myself). So if you are a fast reader much less time will be required.

 

Now that you have built your own server the next step is to build a client so that you can experiment with network programming in Java. Luckily for you there is a tutorial on this site that will tell you how to do just that. The link to the tutorial is below:

https://chafflube.wordpress.com/2012/01/16/how-to-build-a-tcp-client-in-java/

Hopefully you can learn from this code and ultimately understand it and incorporate it into your future Java programs. Good luck with your adventure learning and using Java and who knows, you might just make a hobby out of it.

This tutorial will describe in great detail how you can build a “Hello World” program in Java on a Windows (and in this case) machine. In case you are an absolute beginner user of Java, a “Hello World” program is a program used to literally display the text, “Hello World” on the screen. By creating such a program a Java programmer can test whether or not their Java installation is installed and functioning correctly and a Java beginner can gain a firm grasp of Java command-line I/O (Input/Output).

 

The block of text below is what is and will be referred to hereafter as, “Code.” The term Code is used to describe a file containing text that is typed in a particular way, using particular keywords, written under specific syntaxes in order to allow a computer to read it and act upon what it reads. The code is one of several ways that a human can “speak” to a computer. More on this at the end of this article.

package helloworld;

/*
* @author Dillon Chaffey
* Website: https://chafflube.wordpress.com
* E-mail: chafflube@hotmail.com
*/

public class HelloWorld {
   
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

 

In the block of code above there is a very short set of instructions. These instructions simply tell the computer, “Hey, could you please write the text, “Hello World!” on the computer user’s screen?” So that you can better understand how this code works, let us learn it a bit at a time.

 

package helloworld;

 

The above line of code tells the computer which “package” this .java code file is. In nearly all cases one program will be comprised of one or more .java files within the same package.

 

/*
* @author Dillon Chaffey
* Website: https://chafflube.wordpress.com
* E-mail: chafflube@hotmail.com
*/

 

The above block of code contains details of the author of the code and does not at all affect the way in which the program runs. This is due to the fact that the block of code is a comment. A comment in Java (and most other programming languages) is used merely to leave notes for anybody editing the code or to temporarily remove code from a program without actually removing it. Comments are very useful, as you will find when you begin to build larger programs.

 

public class HelloWorld {

 

The above line of code is the beginning of what is called a “class definition.” A class definition does what its name suggests, defines a class. A class in Java is a block of code that contains one or more “methods.” A method in Java is a block of code that “does something.” In the case of the line of code above, a “public” class with the name “HelloWorld” is created. Public meaning that it can be accessed from any .java file within the same package. The “{“ after “HelloWorld” is an indication that a method is about to be defined.

 

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }

 

The above block of code is what is called the “main method.” The main method is a special method in that it is always the first method to have its code run unless the programmer specifies otherwise. The first line is used to create a public, static, void method with the name “main,” which returns a string array named “args”. Similarly to defining a class, defining a method also requires that the programmer inserts a “{“ after his declaration of the method. The second line contains the actual code that causes the computer to print the text “Hello World!” Finally the “{“ on the final line indicates the end of the main method. Confusing? Don’t worry, it will all make sense if you keep tinkering with the language.

 

}

 

Finally the closing “}” indicates that the end of the class has been reached. At this point the computer will exit the program as it no longer has any code to execute.

 

Although it has been said earlier in this article that the code is read by the computer and the computer acts upon what the code contains, the computer does not read the code that we write directly. Why? Because all code must first be “compiled.” Compiling code is described in more detail below.

 

Compiling Java code

When Java code is compiled it is converted from a code that we can understand to a code that the computer can understand. In the case of Java, the source we type is stored in files with a .java extension and when the code is compiled, the compiled code is stored in a file with a .class extension.

 

When code is compiled into .class files the computer user is able to run the code by using their JVM (Java Virtual Machine). The Java Virtual Machine is used to turn our .class files into “binary” code. Binary code is the language of computers and is often seen in crime scene investigation movies. Binary code can be easily distinguished by chains of “1” and “0.” Like below:

11010010

 

The binary code is then read by the computer what it has to do. In the case of this program, print the text “Hello World!” on the computer user’s screen.

 

I hope that you have benefited from this Java tutorial and have become more interested in learning the Java language. Also, keep in mind, learning Java takes time, but it is a very rewarding experience. Good luck and stay tuned to Chafflube’s Tech Blog for more Java code tutorials.

%d bloggers like this: