How do I create and delete a file in JDK 7?

In this example you’ll learn how to create and delete a file. Using the new Files class helper from the JDK 7 you can create a file using the Files.createFile(Path) method. To delete a file you can use the Files.delete(Path) method.

Before create a file and delete a file we can check to see if the file is exist or not using the Files.exists(Path) method. In the code snippet below we’ll create a file when the file is not exist. And we’ll delete the file if the file is exist.

package org.kodejava.example.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateDeleteFile {
    public static void main(String[] args) {
        try {
            // Create a config.cfg file under D:Temp directory.
            Path path = Paths.get("D:/Temp/config.cfg");
            if (!Files.exists(path)) {
                Files.createFile(path);
            }

            // Delete the path.cfg file specified by the Path.
            if (Files.exists(path)) {
                Files.delete(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I delete entity object in JPA?

The following code example show you how to delete or remove entity object from database using JPA. The first class that we are going to create is ArtistDaoImpl which implements ArtistDao. This DAO class handles the delete process either by the entity Id or by the entity object itself. We define the delete process in deleteById(Long id) and delete(Artist artist) methods.

In those methods we call the EntityManager.remove() method. This method of EntityManager will taking care of removing the entity object from our database. Let’s see the DAO code below:

package org.kodejava.example.jpa.dao;

import org.kodejava.example.jpa.entity.Artist;

import java.util.List;

public interface ArtistDao {
    Artist findById(Long id);

    void save(Artist artist);

    void update(Artist artist);

    List<Artist> getArtists();

    void deleteById(Long id);

    void delete(Artist artist);
}
package org.kodejava.example.jpa.dao.impl;

import org.kodejava.example.jpa.dao.ArtistDao;
import org.kodejava.example.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List;

public class ArtistDaoImpl implements ArtistDao {
    private EntityManager manager;

    public ArtistDaoImpl(EntityManager manager) {
        this.manager = manager;
    }

    /**
     * Find Artist based on the entity Id.
     *
     * @param artistId the artist Id.
     * @return Artist.
     * @throws EntityNotFoundException when no artist is found.
     */
    public Artist findById(Long artistId) {
        Artist artist = manager.find(Artist.class, artistId);
        if (artist == null) {
            throw new EntityNotFoundException("Can't find Artist for ID "
                + artistId);
        }
        return artist;
    }

    @Override
    public void save(Artist artist) {
        manager.getTransaction().begin();
        manager.persist(artist);
        manager.getTransaction().commit();
    }

    /**
     * Update Artist information.
     *
     * @param artist an Artist to be updated.
     */
    @Override
    public void update(Artist artist) {
        manager.getTransaction().begin();
        manager.merge(artist);
        manager.getTransaction().commit();
    }

    @Override
    @SuppressWarnings(value = "unchecked")
    public List<Artist> getArtists() {
        Query query = manager.createQuery("select a from Artist a", Artist.class);
        return query.getResultList();
    }

    /**
     * Delete artist by their Id.
     *
     * @param id the artist Id.
     */
    @Override
    public void deleteById(Long id) {
        Artist artist = manager.find(Artist.class, id);
        if (artist != null) {
            manager.getTransaction().begin();
            manager.remove(artist);
            manager.getTransaction().commit();
        }
    }

    /**
     * Delete artist entity.
     *
     * @param artist the object to be deleted.
     */
    @Override
    public void delete(Artist artist) {
        manager.getTransaction().begin();
        manager.remove(artist);
        manager.getTransaction().commit();
    }
}

After defining the delete methods in the ArtistDao class we create a simple program to demonstrate both of them. In this program we start by create the EntityManagerFactory object from the defined persistence unit in the persistence.xml file. Then we create the EntityManager object and we pass it to our ArtistDaoImpl object. And then we call the delete methods to remove entity from the database.

To show you the result of the delete process we print out the artist data before and after the delete method is called.

package org.kodejava.example.jpa;

import org.kodejava.example.jpa.dao.ArtistDao;
import org.kodejava.example.jpa.dao.impl.ArtistDaoImpl;
import org.kodejava.example.jpa.entity.Artist;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class EntityRemoveDemo {
    public static final String PERSISTENCE_UNIT_NAME = "music";

    public static void main(String[] args) {
        EntityManagerFactory factory =
            Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager manager = factory.createEntityManager();

        ArtistDao dao = new ArtistDaoImpl(manager);
        System.out.println("Before Delete:");
        printArtists(dao.getArtists());

        // Remove artist with Id = 1.
        dao.deleteById(1L);

        // Remove artist with Id = 2.
        Artist artist = dao.findById(2L);
        dao.delete(artist);

        System.out.println("After Delete:");
        printArtists(dao.getArtists());
    }

    private static void printArtists(List<Artist> artists) {
        for (Artist artist : artists) {
            System.out.println("Artist = " + artist);
        }
    }
}

Here is the result of our code snippet. It shows the number of records before and after the delete process.

Before Delete:
Artist = Artist{id=1, name='Bon Jovi'}
Artist = Artist{id=2, name='Mr. Big'}
Artist = Artist{id=3, name='Metallica'}
After Delete:
Artist = Artist{id=3, name='Metallica'}

Maven Dependencies

<dependencies>
    <!-- https://search.maven.org/remotecontent?filepath=javax/persistence/javax.persistence-api/2.2/javax.persistence-api-2.2.jar -->
    <dependency>
        <groupId>javax.persistence</groupId>
        <artifactId>javax.persistence-api</artifactId>
        <version>2.2</version>
    </dependency>
    <!-- https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.4.1.Final/hibernate-core-5.4.1.Final.jar -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.1.Final</version>
    </dependency>
    <!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

Maven Central
Maven Central
Maven Central

How do I remove some characters from a StringBuffer?

The example below show you to remove some elements of the StringBuffer. We can use the delete(int start, int end) method call to remove some characters from the specified start index to end end index. We can also remove a character at the specified index using the deleteCharAt(int index) method call.

package org.kodejava.example.lang;

public class StringBufferDelete {
    public static void main(String[] args) {
        String text = "Learn Java by Examples";

        // Creates a new instance of StringBuffer and initialize
        // it with some text.
        StringBuffer sb = new StringBuffer(text);
        System.out.println("Original text  = " + sb.toString());

        // We'll remove a sub string from this StringBuffer starting
        // from the first character to the 10th character.
        sb.delete(0, 10);
        System.out.println("After deletion = " + sb.toString());

        // Removes a char at a specified index from the StringBuffer.
        // In the example below we remove the last character.
        sb.deleteCharAt(sb.length() - 1);
        System.out.println("Final result   = " + sb.toString());
    }
}

Output of the program is:

Original text  = Learn Java by Examples
After deletion =  by Examples
Final result   =  by Example

How do I delete persistent object in Hibernate?

Continuing the previous example How do I get object from database in Hibernate?, we now add the delete function in our LabelManager class.

package org.kodejava.example.hibernate.app;

import org.hibernate.Query;
import org.hibernate.Session;
import org.kodejava.example.hibernate.model.Label;

import java.util.List;

public class LabelManager {
    public void deleteLabel(Long id) {
        // Load the object to be deleted
        Label label = getLabel(id);

        // We get the current session and delete the Label object from 
        // database.
        Session session = 
            SessionFactoryHelper.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.delete(label);
        session.getTransaction().commit();
    }
}
package org.kodejava.example.hibernate.app;

import org.kodejava.example.hibernate.model.Label;

import java.util.Date;

public class DeleteDemo {
    public static void main(String[] args) {
        LabelManager manager = new LabelManager();

        // Creates a Label object we are going to stored in the database.
        // We set the name and created date information.
        Label label = new Label();
        label.setName("Sony Music");
        label.setCreated(new Date());

        // Call the LabelManager saveLabel method.
        manager.saveLabel(label);

        // Read the object back from database.
        label = manager.getLabel(label.getId());
        System.out.println("Label = " + label);

        manager.deleteLabel(label.getId());
    }
}

Maven Dependencies

<dependencies>
    <!--https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/5.4.1.Final/hibernate-core-5.4.1.Final.jar-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <!--https://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-ehcache/5.4.1.Final/hibernate-ehcache-5.4.1.Final.jar-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    <!--https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

Maven Central
Maven Central

How do I remove substring from StringBuilder?

This example demonstrate you how to use the StringBuilder delete(int start, int end) and deleteCharAt(int index) to remove a substring or a single character from a StringBuilder.

package org.kodejava.example.lang;

public class StringBuilderDelete {
    public static void main(String[] args) {
        StringBuilder lipsum = new StringBuilder("Lorem ipsum dolor sit " +
                "amet, consectetur adipisicing elit.");
        System.out.println("lipsum = " + lipsum.toString());

        // We'll remove a substring from this StringBuilder starting from
        // the first character to the 28th character.
        lipsum.delete(0, 28);
        System.out.println("lipsum = " + lipsum.toString());

        // Removes a char from the StringBuilder. In the example below we
        // remove the last character.
        lipsum.deleteCharAt(lipsum.length() - 1);
        System.out.println("lipsum = " + lipsum.toString());
    }
}

The result of the code snippet above:

lipsum = Lorem ipsum dolor sit amet, consectetur adipisicing elit.
lipsum = consectetur adipisicing elit.
lipsum = consectetur adipisicing elit

How do I delete record from table?

In this example we are showing you how to delete a record from table in the database. We use a standard JDBC library for this purpose. For the database we use MySQL, you can use any type of database you want. All you need to do is to find the JDBC driver for the database and configure it accordingly.

So here is the code example for deleting records from a table in database.

package org.kodejava.example.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DeleteRecordExample {
    public static void main(String[] args) {
        // This is our connection url to MySQL database, where jdbc is the
        // prefix for all jdbc connection. The mysql sub telling that we
        // are using MySQL database. Localhost is where our database is
        // reside and kodejava is our database name.
        String url = "jdbc:mysql://localhost/kodejava";

        // To connect to a database we will need a user and password for
        // the database server to allow us to manipulate its database.
        String username = "root";
        String password = "";

        // Then we ask a connection from the DriverManager by passing
        // the connection URL and the password.
        try (Connection connection =
                 DriverManager.getConnection(url, username, password)) {

            // To delete records from tables we create an SQL delete command.
            // The question mark that we used in the where clause will be the
            // holder of value that will be assigned by PreparedStatement
            // class.
            String sql = "DELETE FROM books WHERE isbn = ?";
            String isbn = "9781617294945";

            // Create a statement object. We use PreparedStatement here.
            PreparedStatement statement = connection.prepareStatement(sql);

            // Pass a value of a isbn that will tell the database which
            // records in the database to be deleted. Remember that when
            // using a statement object the index parameter is start from
            // 1 not 0 as in the Java array data type index.
            statement.setString(1, isbn);

            // Tell the statement to execute the command. The executeUpdate()
            // method for a delete command returns number of records deleted
            // as the command executed in the database. If no records was
            // deleted it will simply return 0
            int rows = statement.executeUpdate();

            System.out.println(rows + " record(s) deleted.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven dependencies

<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

Maven Central

How do I delete a file in Java?

In this example you will see how to delete a file in Java. To delete a file we start by creating a File object that represent the file to be deleted. We use the exists() method to check if the file is exists before we try to delete it.

To delete the file we call the delete() method of the File object. If the file was successfully deleted the method will return a boolean true result, otherwise it will return false. Let’s try the code snippet below.

package org.kodejava.example.io;

import java.io.File;

public class FileDeleteExample {
    public static void main(String[] args) {
        // When want to delete a file named readme.txt
        File file = new File("write.txt");

        // Checks if the file is exists before deletion.
        if (file.exists()) {
            System.out.println("Deleting " + file.getAbsolutePath());
            // Use the delete method to delete the given file.
            boolean deleted = file.delete();
            if (deleted) {
                System.out.println(file.getAbsolutePath() + " was deleted.");
            }
        } else {
            System.out.println(file.getAbsolutePath() + " not found.");
        }
    }
}