Java

Examples, hints, and tips to help you code better in Java.

  1. Delete a file or directory

    Deleting a file or directory in Java is pretty simple. Create a File object and call the .delete() method on it.

    import java.io.File;
     
    File file = new File(filePath);
    file.delete();

    The .delete() method:
    Returns true if the file/directory is deleted successfully
    Returns false if the file/directory is not deleted (ie. file not found, file is open)
    Throws a SecurityException if the application has insufficient permissions to delete the file/directory.

  2. Read a text file using readLine()

    One of the simplest ways to read in a text file in Java is to use the readLine() method to read one line at a time. In this example the file is opened with a FileReader, buffered with a BufferedReader, and then read in using the readLine() method.

    import java.io.*;
     
    public class ReadTextFile {
     
        public static void main(String[] args) {
     
            StringBuilder contents = new StringBuilder();
     
            try {
                BufferedReader input =  new BufferedReader(new FileReader("C:\\Temp\\myFile.txt"));

  3. For loop

    This is an example of a typical for loop.

    for( int var=0; var<10; var++) {
        // Code to execute    
    }

    The initiation of the for loop includes three different command seperated be semicolons.

    First
    In this example an integer named var is created and initialized to  ;
    If we are using a variable that has already being instantiated just enter the name of the variable and optionally assign it a new value.
    ie.

    int var = 0;
    for(var=2; var<10; var++) {
        // Code to execute    
    }

  4. Hello World

    A basic java program.

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

Syndicate content