Easy Work With File Stream Processing Using Custom Java Class To Store & Retrieve File

Introduction

Oftentimes, application needs to store documents i.e files or images on database record or file copy under specific folder.

Developers use Streaming class i.e OutputStream, InputStream, FileOutputStream, FileInputStream, BufferedOutputStream, BufferedInputStream.
Count of code’s line is a kind of lot. Although there are good examples spread out in a web, sometimes java beginners might get confused.

So, I made custom java class to make file stream processing simple. I call the class with ‘FileStreamProc’. This class can stored documents to database or file via ftp or copy method. Also retrieving documents from data source.
We don’t have to bother anymore about those streaming classes above when we use FileStreamProc class. However, those classes are inside FileStreamProc off course. Main functions of FileStreamProc are Upload, Download, and Delete for storing, retrieving and deleting respectively.
We only have to write 2 lines of codes to store a file to database.
In example of FileStreamProc usage:

FileStreamProc fp = new FileStreamProc("doc1");
fp.Upload("D:\\folder\\SOP.pdf", ProcessMethod.Database);

‘doc1’ refers to document ID value. ‘D:\folder\SOP.pdf’ is file path value. Pretty simple right ?

Process Method

There are three option of process method for storing & retrieving file in this custom class which are Database or Ftp or Basic Copy.
If you use Database then set your database server and when you use ftp then set your ftp server. Otherwise Basic Copy then you might have to setup Shared folder and also its security.

Download

I made this FileStreamProc Class using NetBeans IDE 7.4 with MySql as database and FileZilla as Ftp server.
You can download FileStreamProc netbeans project here. Please use it at your own risk.

FileStreamProc Class Code – Explanation

At first, we have to make Library Java Project ‘FileStreamProc’. This project contains three class files. DBHandler, FTPHandler and FileStreamProc.

DBHandler used to store, retrieve and delete file to & from database record. FTPHandler do the same only processed via Ftp command and save as file not a blob (record).

Both of them are internal class. They cannot be accessed by public. DBHandler & FTPHandler used by FileStreamProc. You can modify DBHandler or FTPHandler easily because files are separated from main class.

As I told you above that I used MySql as database server, so that driver, connection and sql syntax on DBHandler class are use MySql style.
I’ve already made table structure to store documents as blob. I have two tables which are documents & blobs.

documents table used to store document id, file name, folder path, processing method. Columns are look like below:
+——-+————–+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+——-+————–+——+—–+———+——-+
| docid | varchar(10) | NO | PRI | | |
| docnm | varchar(255) | YES | | NULL | |
| docfd | text | YES | | NULL | |
| docpm | varchar(3) | YES | | NULL | |
+——-+————–+——+—–+———+——-+

This documents table also used for other process method i.e ftp or basic copy to save file name, folder path & its related processing method.
To create documents table please use this statement:

CREATE TABLE `documents` (
  `docid` varchar(10) NOT NULL DEFAULT '',
  `docnm` varchar(255) DEFAULT NULL,
  `docfd` text,
  `docpm` varchar(3) DEFAULT NULL,
  PRIMARY KEY (`docid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

blobs table used to store document blob record. Columns are below:
+——-+————-+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+——-+————-+——+—–+———+——-+
| docid | varchar(10) | YES | MUL | NULL | |
| blobf | mediumblob | YES | | NULL | |
+——-+————-+——+—–+———+——-+

This table only used by Database processing method.
To create blobs table please use this statement:

CREATE TABLE `blobs` (
  `docid` varchar(10) DEFAULT NULL,
  `blobf` mediumblob,
  KEY `docid` (`docid`),
  CONSTRAINT `blobs_ibfk_1` FOREIGN KEY (`docid`) REFERENCES `documents` (`docid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Here’s DBHandler class code:

package com.wordpress.gugiaji.java.Stream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

class DBHandler {
    
    static final String jdbc_driver = "com.mysql.jdbc.Driver";
    private String db_url;
    private String user; private String pwd;
    private Connection conn;
    private Statement stmt;
    private PreparedStatement psmnt;
    public DBHandler(String server, String dbname, String user, String pwd) {
        try {
            db_url = "jdbc:mysql://" + server + ":3306/" + dbname;
            conn = null;
            stmt = null;
            this.user = user;
            this.pwd = pwd;
            
            Class.forName(jdbc_driver);
            
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void OpenDB() {
        try {
            conn = DriverManager.getConnection(db_url,user, pwd);
            stmt = conn.createStatement();
            psmnt = null;
        } catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public int SaveFilePath(String file_id, String filename, String filefolder, String processmethod) {
        int result = 0;
        try {
            OpenDB();
            String query = "select count(*) as cnt from documents where docid='" + file_id + "'";
            ResultSet rs = stmt.executeQuery(query);
            int cnt=0;
            if (rs.next()) {
                cnt = rs.getInt(1);
            }
            rs.close();
            if (cnt==0) {
                query = "insert into documents (docid, docnm, docfd, docpm) values ('" + file_id + "','" + filename + "','" + filefolder.replace("\\","\\\\") + "','" + processmethod + "')";
            } else {
                query = "update documents set docnm='" + filename + "', docfd='" + filefolder.replace("\\","\\\\") + "', docpm='" + processmethod + "' where docid='" + file_id + "'";   
            }
            stmt.executeUpdate(query);
            DBClose();
            result = 1;
        } catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
    
    public ProcessMethod GetProcessMethod(String file_id) {
        ProcessMethod result = null;
        try {
            OpenDB();
            String query = "select docpm from documents where docid='" + file_id + "'";
            ResultSet rs = stmt.executeQuery(query);
            String strresult="";
            if (rs.next()) {
                strresult = rs.getString("docpm");
            }
            rs.close();
            DBClose();
            
            switch (strresult) {
                case "db":
                    result = ProcessMethod.Database;
                    break;
                case "ftp":
                    result = ProcessMethod.Ftp;
                    break;
                case "cpy":
                    result = ProcessMethod.BasicCopy;
                    break;
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
    public String GetSavedFilePath(String file_id) {
        String result = "";
        try {
            OpenDB();
            String query = "select docnm, docfd from documents where docid='" + file_id + "'";
            ResultSet rs = stmt.executeQuery(query);
            
            if (rs.next()) {                
                result = (rs.getObject("docfd")!="null" ? rs.getString("docfd") + (strprocessmethod=="ftp" ? "/":File.separator) : "") + rs.getString("docnm");
            }
            rs.close();
            DBClose();
        } catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
    
    public int SaveBlob(String file_id, String fileabsolutepath) {
        int result = 0;
        try {
            File f = new File(fileabsolutepath);
            String filename = "";
            if (f.isAbsolute()) {
                   filename = f.getName();
                   
            }
            this.SaveFilePath(file_id, filename, "", "db");
            OpenDB();                     
            
            File docf = new File(fileabsolutepath);
            FileInputStream fs = new FileInputStream(docf);
            int bloblen = (int) docf.length();
            
            String query = "select count(*) as cnt from blobs where docid='" + file_id + "'";
            ResultSet rs = stmt.executeQuery(query);
            int countrow = 0;
            if (rs.next()) {
                countrow = rs.getInt("cnt");
            }
            if (countrow==0) {
                query = "insert into blobs (docid, blobf) values ('" + file_id + "', ?)";
            } else {
                query = "update blobs set blobf=? where docid='" + file_id + "'";            
            }
            psmnt = conn.prepareStatement(query);            
           
            psmnt.setBinaryStream(1, fs, bloblen);                        
            result = psmnt.executeUpdate();
            
            fs.close();                        
            DBClose();
        } catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
            
        } catch (IOException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);            
        }
        
        return result;        
    }    
    
    public File GetBlob(String file_id, String folderpath) {
        
        String filename="";
        File f = null;
        try {
            String query = "select blobf from blobs where docid='" + file_id + "'";
            OpenDB();
            ResultSet rs = stmt.executeQuery(query);
            if (rs.next()) {
                filename = this.GetSavedFilePath(file_id);
                Blob b = rs.getBlob(1);
                f = new File(folderpath + File.separator + filename);
                FileOutputStream fos = new FileOutputStream(f);
                if (!f.exists()) {
                    f.createNewFile();
                }
                byte[] contentbytes = b.getBytes(1, (int)b.length());
                fos.write(contentbytes);
                fos.flush();
                fos.close();
                b.free();
            }
            rs.close();
            DBClose();
            
        } catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
        return f;
    }
    
    public int Delete(String file_id) {
         int result = 0;
        try {
            OpenDB();
            String query = "delete from documents where docid='" + file_id + "'";
            stmt.executeUpdate(query);
            
            query = "delete from blobs where docid='" + file_id + "'";
            stmt.executeUpdate(query);
            
            DBClose();
            result = 1;
        } catch (SQLException ex) {
            Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
     private void DBClose() throws SQLException {
        if (stmt!= null) {
            stmt.close();
        }
        
        if (psmnt != null) {
            psmnt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}

DBHandler class contains SaveBlob & GetBlob method to store & retrieve file in database. Also this class has SaveFilePath & GetSavedFilePath to save & get file name, path, process method & document ID.
DBHandler can be used not only for database process but also to save details for ftp or basic copy operation.

FTPHandler class code:

package com.wordpress.gugiaji.java.Stream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

class FTPHandler {
    private String ftpserver;
    private String ftpuser;
    private String ftppasswd;
    public FTPHandler(String ftpserver, String ftpuser, String ftppasswd) {
        this.ftpserver = ftpserver;
        this.ftpuser = ftpuser;
        this.ftppasswd = ftppasswd;
    }
    
    public int ftpUpload(String sourcefilepath, String ftptargetfolder) {
        FTPClient ftp = new FTPClient();
        File f = null;
        String filename = "";
        int result = 0;
        try {
            ftp.connect(ftpserver,21);
            ftp.login(ftpuser, ftppasswd);
            ftp.enterLocalPassiveMode();            
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            
            InputStream _is = new FileInputStream(new File(sourcefilepath));
            f = new File(sourcefilepath);
            if (f.isAbsolute()) {
                filename = f.getName();
                
            }
            ftp.storeFile(ftptargetfolder + "/" + filename, _is);
            ftp.logout();
            ftp.disconnect();
           
            result = 1;
        } catch (IOException ex) {
            Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
         return result;
    }
    public File ftpDownload(String sourceftpfilepath, String targetfolderpath) {
        FTPClient ftp = new FTPClient();
        File dwln=null;
        try {
            
            ftp.connect(ftpserver,21);
            ftp.login(ftpuser, ftppasswd);
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            
            int lastpos_sep = sourceftpfilepath.lastIndexOf("/");            
            String filename = "";
            if (lastpos_sep > -1) {
                filename = sourceftpfilepath.substring(lastpos_sep+1);
            } else {
                filename = sourceftpfilepath;
                
            }
            
            dwln = new File(targetfolderpath + File.separator + filename);
            OutputStream _os = new BufferedOutputStream(new FileOutputStream(dwln));
            ftp.retrieveFile(sourceftpfilepath, _os);
            _os.close();
            
            ftp.logout();
            ftp.disconnect();
            
        } catch (IOException ex) {
            Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return dwln;
    }
    public int ftpDelete(String sourcefilepath) {
        int result = 0;
        FTPClient ftp = new FTPClient();
        try {
            
            ftp.connect(ftpserver,21);
            ftp.login(ftpuser, ftppasswd);
            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.deleteFile(sourcefilepath);
            ftp.logout();
            ftp.disconnect();
            
            result = 1;
        } catch (IOException ex) {
            Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
        return result;
    }
}

FTPHandler used to store & retrieve file via ftp operation. This class has ftpUpload & ftpDownload to Upload & Download to/from server.
I used apache common net API to help me develop ftp operation. This API can be downloaded at http://commons.apache.org/proper/commons-net/download_net.cgi.

DBHandler and FTPHandler class have Delete method to remove file from specific record or physical file.

Now, the main class ‘FileStreamProc’:

package com.wordpress.gugiaji.java.Stream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileStreamProc {
    private String _fileid;
    private DBHandler _dbh;
    private Boolean usedb;
    private ProcessMethod processmethod;
        
    public FileStreamProc() {
        usedb = false;        
    }
    
    public FileStreamProc(String server, String db, String userid, String passwd, String file_id) {
        _dbh = new DBHandler(server, db, userid, passwd);
        _fileid = file_id;
        usedb = true;
        
    }
    
    public int Upload(String sourcefilepath, ProcessMethod processmethod) {
        int result = 0;
        if (processmethod==ProcessMethod.Database) {
           
            result = SavefileToDB(sourcefilepath);
        } else {
            try {
                throw new Exception("Error. Your process method is not db. Use 'Upload(sourcefilepath, targetfolderpath, processmethod)' method");
            } catch (Exception ex) {
                Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
        return result;
    }
    
    public int Upload(String sourcefilepath, String targetfolderpath, ProcessMethod processmethod) {
        int result = 0;
        switch (processmethod) {
            case Database:
                try {
                    throw new Exception("Error. Your process method is db. Use 'Upload(sourcefilepath, processmethod)' method");
                } catch (Exception ex) {
                    Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
                }
                break;
            case Ftp:
                result = ftpUpload(sourcefilepath, targetfolderpath);
                break;
            case BasicCopy:
                result = CopyFileToLocation(sourcefilepath, targetfolderpath);
                break;
        }
        return result;
    }
    
    public File Download(String targetfolderpath) {
        File result = null;
        try {
            if (!usedb) throw new Exception("Error. You dont have file_id. use 'Download(sourcefilepath, targetfolderpath, processmethod)' method instead");
            if (targetfolderpath=="") throw new Exception("Error. targetfolderpath cannot be empty");
            processmethod = _dbh.GetProcessMethod(_fileid);
            switch (processmethod) {
                case Database:
                    result = GetfileFromDB(targetfolderpath);
                    break;
                case Ftp:
                    result = ftpDownload(targetfolderpath);
                    
                    break;
                case BasicCopy:
                    result = GetFileFromLocation(targetfolderpath);
                    break;
            }
            
        } catch (Exception ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
    
    public File Download(String sourcefilepath, String targetfolderpath, String processmethod) {
        File result = null;
        try {
            if (usedb) throw new Exception("Error. You specify file_id. use 'Download(targetfolderpath)' method instead");
            if (targetfolderpath=="") throw new Exception("Error. targetfolderpath cannot be empty");
            switch (processmethod) {
                case "db":
                    throw new Exception("Error. Your process method is db. use 'Download(targetfolderpath)' method instead");
                case "ftp":
                    result = ftpDownload(sourcefilepath,targetfolderpath);
                    break;
                case "cpy":
                    int s = Copy(sourcefilepath, targetfolderpath);
                    if (s>0) {
                        int lastpos_sep = sourcefilepath.lastIndexOf(File.separator);
                        String filename = sourcefilepath.substring(lastpos_sep+1);
            
                        result = new File(targetfolderpath + File.separator + filename);
                    }
                    break;
            }
            
        } catch (Exception ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
    public int Delete() {
        int result = 0;
        try {
            
            if (!usedb) throw new Exception("Error. You dont have file_id. use 'Delete(sourcefilepath, processmethod)' method");
            processmethod = _dbh.GetProcessMethod(_fileid);
            String savedfilepath = _dbh.GetSavedFilePath(_fileid);
            if (!savedfilepath.equals("")) {
                switch (processmethod) {
                    case BasicCopy:
                        result = Delete(savedfilepath, processmethod);
                        break;
                    case Ftp:
                        result = ftpDelete(savedfilepath);
                        break;
                    case Database:
                        result = 1;            
                        break;
                }
                
                if (result==1) {
                    result = _dbh.Delete(_fileid);
                }
            }
            
        } catch (Exception ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
    
    public int Delete(String sourcefilepath, ProcessMethod processmethod) {
        int result = 0;
        try {
            if (usedb) throw new Exception("Error. You have file_id. Use 'Delete()' without argument method.");
            switch (processmethod) {
            case Database:
                throw new Exception("Error. Your process method is db. Use 'Delete()' without argument method.");
                
            case Ftp:
                result = this.ftpDelete(sourcefilepath);
                break;
            case BasicCopy:
                File f = new File(sourcefilepath);
                if (f.exists()) {
                    f.delete();
                    result = 1;
                }
                break;
            }
            result = 1;
           
        } catch (Exception ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        }
         return result;
    }
    
    
    
    private int SavefileToDB(String sourcefilepath) {
        
        if (usedb) {
            return _dbh.SaveBlob(_fileid, sourcefilepath);        
        } else {
            return 0;
        }
    }
    
    private File GetfileFromDB(String folderpath) {
        
        if (usedb) {
            return _dbh.GetBlob(_fileid, folderpath);
        } else {
            return null;
        }
    }
    
    private String ftpserver;
    private String ftpuser;
    private String ftppasswd;
    public void set_ftpserver(String server) {
        ftpserver = server;
    }
    public void set_ftpuser(String userid) {
        ftpuser = userid;
    }
    public void set_ftppasswd(String passwd) {
        ftppasswd = passwd;
    }
    private int ftpUpload(String sourcefilepath, String ftptargetfolder) {
        FTPHandler fh = new FTPHandler(ftpserver, ftpuser, ftppasswd);
        
        int result = 0;
        String filename="";
        File f = new File(sourcefilepath);
        if (f.isAbsolute()) {
             filename = f.getName();

        } else {
            return result;
        }
        
        result = fh.ftpUpload(sourcefilepath, ftptargetfolder);
        if (result == 1) {         
            result = (usedb==true ? _dbh.SaveFilePath(_fileid, filename, ftptargetfolder, "ftp") : 1);
        }
                   
        return result;
    }
    
       
    private File ftpDownload(String targetfolderpath) {
        File f = null;
        try {
            if (!usedb) throw new Exception("Error. You dont have file_id. Use 'ftpDownload(sourceftpfilepath, targetfolderpath)' method");
            String savedfilepath = _dbh.GetSavedFilePath(_fileid);  
            FTPHandler fh = new FTPHandler(ftpserver, ftpuser, ftppasswd);
            f= fh.ftpDownload(savedfilepath,targetfolderpath);
            
        } catch (Exception ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        }
        return f;
    }
    
    private File ftpDownload( String sourceftpfilepath, String targetfolderpath) {
        
        File f = null;
        FTPHandler fh = new FTPHandler(ftpserver, ftpuser, ftppasswd);
        f= fh.ftpDownload(sourceftpfilepath,targetfolderpath);
        
        return f;
    }
    
    private int Copy(String sourcefilepath, String targetfilepath) {
        InputStream _is = null;
        OutputStream _os = null;
        int result = 0;
        try {
        
            File source = new File(sourcefilepath);
            File target = new File(targetfilepath);
            _is = new FileInputStream(source);
            _os = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = _is.read(buffer))>0) {
                _os.write(buffer, 0, length);
            }
            result = 1;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                _is.close();
                _os.close();
            } catch (IOException ex) {
                Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        return result;
    }
    
    private int CopyFileToLocation(String sourcefilepath, String targetfolderpath) {
        int result = 0;
        try {
            String targetfilepath;
            
            int lastpos_sep = sourcefilepath.lastIndexOf(File.separator);
            String filename = sourcefilepath.substring(lastpos_sep+1);
            targetfilepath = targetfolderpath + File.separator + filename;
                   
            result = Copy(sourcefilepath, targetfilepath);
            
            if (result==1 && usedb) {
                
                result = _dbh.SaveFilePath(_fileid, filename, targetfolderpath, "cpy");
            }
        } catch (Exception ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return result;
    }
    
    private File GetFileFromLocation(String targetfolderpath) {
        File f = null;
        try {
            if (!usedb) throw new Exception("Error. Please specify file id");
            String savedfilepath = _dbh.GetSavedFilePath(_fileid);
            File savedfile = new File(savedfilepath);
            if (savedfile.exists()) {
                String targetfilepath = targetfolderpath + File.separator + savedfile.getName();
                int result = Copy(savedfilepath, targetfilepath);
                f = new File(targetfilepath);
            }
            
        } catch (Exception ex) {
            Logger.getLogger(FileStreamProc.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return f;
    }
    
    private int ftpDelete(String sourcefilepath) {
        int result = 0;
        FTPHandler fh = new FTPHandler(ftpserver, ftpuser, ftppasswd);
        result = fh.ftpDelete(sourcefilepath);
        
        return result;
    }
    
}

FileStreamProc can be used to process file that has file info in database or plain file processing.
Plain file processing means no database included. It is only use ftp or basic copy process method.

FileStreamProc has 2 constructors. One without argument at all and second use server details and also file_id.
Constructor without argument will acts plain file processing. Otherwise database used.

Main public functions are Upload, Download and Delete. Private functions are just to implement DBHandler & FTPHandler class inside FileStreamProc to make up public methods.
Main functions have overloaded function. It is used to seperate between using database & plain file processing.

At the developer end user point of view, only this FileStreamProc class to be considered.

FileStreamProc Usage Example

  1. Storing file to database record
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileStreamProc fp = new FileStreamProc("localhost","test","root","","doc1");
    int result = fp.Upload("D:\\Folder\\your_db_document.pdf", ProcessMethod.Database);
    
  2. Retrieving file from record
    import java.io.File;
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileStreamProc fp = new FileStreamProc("localhost","test","root","","doc1");
    File f = fp.Download("D:\\AnotherFolder");
    
  3. Delete file from record
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileStreamProc fp = new FileStreamProc("localhost","test","root","","doc1");
    int s = fp.Delete();
    
  4. Copying / Uploading file via ftp
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileStreamProc fp = new FileStreamProc("localhost","test","root","","doc2");
    int result = fo.Upload("D:\\Folder\\your_document.xls","temp", ProcessMethod.Ftp);
    
  5. Downloading file via ftp
    import java.io.File;
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileStreamProc fp = new FileStreamProc("localhost","test","root","","doc2");
    File f = fp.Download("D:\\AnotherFolder");
    
  6. Copying file using Basic Copy
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileStreamProc fp = new FileStreamProc("localhost","test","root","","doc3");
    int result = fo.Upload("D:\\Folder\\your_copy_document.doc","D:\\CopiedFolder", ProcessMethod.BasicCopy);
    
  7. Uploading file via ftp and not using record of file details (plain file processing)
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileOperation fp = new FileOperation();
    int result = fo.Upload("D:\\Folder\\your_ftp_document.xls","temp", ProcessMethod.Ftp);
    
  8. Downloading file via ftp and not using record of file details (plain file processing)
    import java.io.File;
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileOperation fp = new FileOperation();
    File f = fp.Download("temp/your_ftp_document.xls", "D:\\AnotherFolder", ProcessMethod.Ftp)
    
  9. Delete physical file via ftp
    import com.wordpress.gugiaji.java.Stream.FileStreamProc;
    import com.wordpress.gugiaji.java.Stream.ProcessMethod;
    
    FileOperation fp = new FileOperation();
    int result= fp.Delete("temp/your_ftp_document.xls", ProcessMethod.Ftp)
    

I think those examples above are pretty simple. We don’t have to worry anymore about code details that make up db records or ftp process.

Align FileStreamProc To Existing Class / Application

FileStreamProc use MySql as database server also documents & blobs table.

If you have another class or table on application that already exist that do for file processing and you want to use this ‘FileStreamProc’ then I suggest for two options below:

  1. If you use MySql then join your existing tables with documents / blobs with one to one relationship with primary key i.e documentid or docid.
    Otherwise, if you are not using MySql then you can connect it in source code based on primary key value.
  2. Or change DBHandler source code directly to fit to your own environment. Try to change only the body of functions not the declaration itself because it is used on main class.

Regards,
Agung Gugiaji

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s