Writing files in Java

I am going to show example which shows how to write a file in Java.
If you want to write some file you should start with FileOutputStream. This class is a concrete subclass of OutputStream.
Example:

package tutorial;

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

/**
 * This class shows how to write a file
 * @author The Developer's Info
 */
public class Main {

    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            String workingDirectory = System.getProperty("user.dir");
            File fileDir = new File(workingDirectory, "src/tutorial");
            File readFile = new File(fileDir, "Main.java");

            File writeFile = new File(fileDir, "CopyFile");

            fileInputStream = new FileInputStream(readFile);

//            fileOutputStream = new FileOutputStream(writeFile, true);
            fileOutputStream = new FileOutputStream(writeFile);

            show(fileInputStream, fileOutputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException ex) {}
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException ex) {}
        }
    }

    /**
     * This method read and write a file
     * @param fileInputStream input stream
     * @param fileOutputStream output stream
     * @throws IOException
     */
    private static void show(FileInputStream fileInputStream, FileOutputStream fileOutputStream) throws IOException {
        byte[] buffer = new byte[1024];
        while (true) {
            int bytesRead = fileInputStream.read(buffer);
            if (bytesRead == -1) {
                break;
            }
            fileOutputStream.write(buffer, 0, bytesRead);
        }
    }
}

I had commented code in line number 26.
This constructor lets you specify whether the file’s contents should be erased before data is written into it (append == false) or whether data is to be tacked onto the end of the file (append == true). You can uncomment this line and comment next line of code and you will see how content is added in the end of the file.

  • Share/Bookmark

Related posts:

  1. Reading files in Java
  2. Multitargeting output streams in Java
  3. Using Filter Streams in Java
  4. Using InputStream in Java
  5. Using Data Streams in Java

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>