Simple Java File Read/Write Example

Here is a simple example of a Java class that will read/write a file byte by byte

/*
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filereader;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
 
/**
 *
 * @author dphegarty
 */
public class Main {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Main m = new Main();
        m.writeFile(m.readFile());
    }
 
    public void writeFile(ByteArrayOutputStream content) {
        File file = null;
        FileOutputStream fis = null;
        DataOutputStream dis = null;
        ByteArrayInputStream inContent = new ByteArrayInputStream(content.toByteArray());
 
        try {
            file = new File("/Users/JSmith/About Stacks.pdf");
            file.createNewFile();
            fis = new FileOutputStream(file);
            dis = new DataOutputStream(fis);
            while (inContent.available() != 0) {
                dis.write(inContent.read());
            }
            dis.flush();
            dis.close();
            inContent.close();
        } catch (Exception ex) {
 
        }
    }
 
    public ByteArrayOutputStream readFile() {
        File file = null;
        FileInputStream fis = null;
        DataInputStream dis = null;
        ByteArrayOutputStream content = new ByteArrayOutputStream();
 
        try {
            file = new File("/Users/JSmith/Documents/About Stacks.pdf");
            fis = new FileInputStream(file);
            dis = new DataInputStream(fis);
            while (dis.available() != 0) {
                content.write(dis.read());
            }
            dis.close();
            fis.close();
        } catch (Exception ex) {
        }
        System.out.println("Size: " + content.size() + " File: " + file.length());
        return content;
    }
}
 

Leave a Reply

jump2top free wordpress themes