How do I read data from a buffer into channel?

In this example you’ll see how to read data from buffer using FileChannel.write() method call. Reading from a buffer means that you are writing data into the channel object. In the snippet below the data from our dummy buffer will be read and written into the result.txt file.

package org.kodejava.io;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class BufferRead {
    public static void main(String[] args) throws Exception {
        FileChannel channel = null;

        try {
            // Define an output file and create an instance of FileOutputStream
            File file = new File("result.txt");
            FileOutputStream fos = new FileOutputStream(file);

            // Create a dummy ByteBuffer which value to be read into a channel.
            ByteBuffer buffer = ByteBuffer.allocate(256);
            buffer.put(new byte[]{65, 66, 67, 68, 69, 70, 71, 72, 73, 74});

            // Change the buffer from writing mode to reading mode.
            buffer.flip();

            // Gets the channel from the FileOutputStream object and read the
            // data available in buffer using channel.write() method.
            channel = fos.getChannel();
            int bytesWritten = channel.write(buffer);
            System.out.println("written : " + bytesWritten);
        } finally {
            if (channel != null && channel.isOpen()) {
                channel.close();
            }
        }
    }
}

How do I copy file?

This example demonstrates how to copy file using the Java IO library. Here we will use the java.io.FileInputStream and it’s tandem the java.io.FileOutputStream class.

package org.kodejava.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyDemo {
    public static void main(String[] args) {
        // Create an instance of source and destination files
        File source = new File("source.pdf");
        File destination = new File("target.pdf");

        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(destination)) {
            // Define the size of our buffer for buffering file data
            byte[] buffer = new byte[4096];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I convert a bean to XML persistence?

package org.kodejava.bean;

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class BeanToXML {
    private Long id;
    private String itemName;
    private String itemColour;
    private Integer itemQuantities;

    public static void main(String[] args) {
        BeanToXML bean = new BeanToXML();
        bean.setId(1L);
        bean.setItemName("T-Shirt");
        bean.setItemColour("Dark Red");
        bean.setItemQuantities(100);

        try {
            XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
                    new FileOutputStream("Bean.xml")));

            // Write an XML representation of the specified object to the output.
            encoder.writeObject(bean);
            encoder.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public String getItemColour() {
        return itemColour;
    }

    public void setItemColour(String itemColour) {
        this.itemColour = itemColour;
    }

    public Integer getItemQuantities() {
        return itemQuantities;
    }

    public void setItemQuantities(Integer itemQuantities) {
        this.itemQuantities = itemQuantities;
    }
}

The XML persistence will be like:

<?xml version="1.0" encoding="UTF-8"?>
<java version="17" class="java.beans.XMLDecoder">
 <object class="org.kodejava.bean.BeanToXML">
  <void property="id">
   <long>1</long>
  </void>
  <void property="itemColour">
   <string>Dark Red</string>
  </void>
  <void property="itemName">
   <string>T-Shirt</string>
  </void>
  <void property="itemQuantities">
   <int>100</int>
  </void>
 </object>
</java>

How do I store properties as XML file?

In the previous example, How do I load properties from XML file? we read properties from XML file. Now it’s the turn on how to store the properties as XML file.

package org.kodejava.io;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class PropertiesToXml {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.setProperty("db.type", "mysql");
        properties.setProperty("db.url", "jdbc:mysql://localhost:3306/kodejava");
        properties.setProperty("db.username", "root");
        properties.setProperty("db.password", "");

        FileOutputStream fos = new FileOutputStream("db-config.xml");
        properties.storeToXML(fos, "Database Configuration", StandardCharsets.UTF_8);
    }
}

The saved XML file will look like the properties file below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>Database Configuration</comment>
    <entry key="db.type">mysql</entry>
    <entry key="db.password"></entry>
    <entry key="db.username">root</entry>
    <entry key="db.url">jdbc:mysql://localhost:3306/kodejava</entry>
</properties>

How do I store objects in file?

This example demonstrates how to use the java.io.ObjectOutputStream and java.io.ObjectInputStream classes to write and read a serialized object. We will create a Book that implements java.io.Serializable interface. The Book class has a constructor that accept all the book detail information.

To write an object to a stream we call the writeObject() method of the ObjectOutputStream class and pass the serialized object to it. To read the object back we call the readObject() method of the ObjectInputStream class.

package org.kodejava.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectStoreExample {

    public static void main(String[] args) {
        // Create instances of FileOutputStream and ObjectOutputStream.
        try (FileOutputStream fos = new FileOutputStream("books.dat");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {

            // Create a Book instance. This book object then will be stored in
            // the file.
            Book book = new Book("0-07-222565-3", "Hacking Exposed J2EE & Java",
                    "Art Taylor, Brian Buege, Randy Layman");

            // By using writeObject() method of the ObjectOutputStream we can
            // make the book object persistent on the books.dat file.
            oos.writeObject(book);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // We have the book saved. Now it is time to read it back and display
        // its detail information.
        try (FileInputStream fis = new FileInputStream("books.dat");
             ObjectInputStream ois = new ObjectInputStream(fis)) {

            // To read the Book object use the ObjectInputStream.readObject() method.
            // This method return Object type data, so we need to cast it back the
            // origin class, the Book class.
            Book book = (Book) ois.readObject();
            System.out.println(book.toString());

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

// The book object will be saved using ObjectOutputStream class and to be read
// back using ObjectInputStream class. To enable an object to be written to a
// stream we need to make the class implements the Serializable interface.
class Book implements Serializable {
    private final String isbn;
    private final String title;
    private final String author;

    public Book(String isbn, String title, String author) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "isbn='" + isbn + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

The result of the code snippet above is:

Book{isbn='0-07-222565-3', title='Hacking Exposed J2EE & Java', author='Art Taylor, Brian Buege, Randy Layman'}