com.testmax.util.FileUtility.java Source code

Java tutorial

Introduction

Here is the source code for com.testmax.util.FileUtility.java

Source

/*
 * Copyright (C) 2014 Artitelly Solutions Inc, www.CloudTestSoftware.com
 *
 * Licensed under the Common Development and Distribution License (CDDL-1.0) (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/CDDL-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.testmax.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileWriter;
import java.io.IOException;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import com.testmax.framework.WmLog;

public class FileUtility {

    public static void writeToFile(String path, String text) {
        try {
            // Create file 
            FileWriter fstream = new FileWriter(path);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(text);
            //Close the output stream
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static boolean createDir(String path) {
        File f = new File(path);
        boolean success = false;
        if (!f.isFile() && !f.exists()) {
            f.mkdirs();
            success = true;
        }
        return (success);

    }

    public static void deleteFile(String file) {
        try {
            File f1 = new File(file);
            boolean success = f1.delete();
            if (!success) {
                WmLog.getCoreLogger().info("Failed to delete file at: " + file);
                System.out.println("Deletion failed.");
            } else {
                WmLog.getCoreLogger().info("Delete file at: " + file);
                System.out.println("Delete file at: " + file);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            WmLog.getCoreLogger().info("Error to delete file " + file + " " + e.getMessage());
        }
    }

    public static void createTextFile(String absolute_path, String text) {
        System.out.println("Creating text file at: " + absolute_path);
        WmLog.getCoreLogger().info("Creating text file at: " + absolute_path);
        try {
            FileWriter file = new FileWriter(new File(absolute_path));
            file.write(text);
            file.close();
            WmLog.getCoreLogger().info("Saved text file at: " + absolute_path);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            WmLog.getCoreLogger().info("Problem occured while saving the HTML Report file html_report.html for "
                    + absolute_path + " " + e.getMessage());
        }

    }

    public static void renameFile(String oldFileName, String newFileName) {
        try {
            File oldName = new File(oldFileName);
            File newName = new File(newFileName);
            if (oldName.renameTo(newName)) {
                WmLog.getCoreLogger().info("Renamed file " + oldFileName + " to " + newFileName);
            } else {
                WmLog.getCoreLogger().info("Failed to renamed file " + oldFileName + " to " + newFileName);
            }
        } catch (Exception e) {
            WmLog.getCoreLogger().info("Could not found file " + oldFileName);
        }
    }

    public static void copyFile(String srFile, String dtFile) {
        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);
            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();

        } catch (FileNotFoundException ex) {
            WmLog.getCoreLogger().info(ex.getMessage() + " in the specified directory.");
            System.out.println(ex.getMessage() + " in the specified directory.");
        } catch (IOException e) {
            WmLog.getCoreLogger().info(e.getMessage());
            System.out.println(e.getMessage());
        }
    }

    public void fileUpload(String url, String filename) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        FileBody fileContent = new FileBody(new File(filename));
        try {
            StringBody comment = new StringBody("Filename: " + filename);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", fileContent);
        httppost.setEntity(reqEntity);
        HttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpEntity resEntity = response.getEntity();
    }

    public static void copyFolder(File src, File dest) throws IOException {

        if (src.isDirectory()) {

            //if directory not exists, create it
            if (!dest.exists()) {
                dest.mkdir();
                System.out.println("Directory copied from " + src + "  to " + dest);
            }

            //list all the directory contents
            String files[] = src.list();

            for (String file : files) {
                //construct the src and dest file structure
                File srcFile = new File(src, file);
                File destFile = new File(dest, file);
                //recursive copy
                copyFolder(srcFile, destFile);
            }

        } else {
            //if file, then copy it
            //Use bytes stream to support all file types
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes 
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }

            in.close();
            out.close();
            System.out.println("File copied from " + src + " to " + dest);
        }
    }

    public static void delete(File file) throws IOException {

        if (file.isDirectory()) {

            //directory is empty, then delete it
            if (file.list().length == 0) {

                file.delete();
                System.out.println("Directory is deleted : " + file.getAbsolutePath());

            } else {

                //list all the directory contents
                String files[] = file.list();

                for (String temp : files) {
                    //construct the file structure
                    File fileDelete = new File(file, temp);

                    //recursive delete
                    delete(fileDelete);
                }

                //check the directory again, if empty then delete it
                if (file.list().length == 0) {
                    file.delete();
                    System.out.println("Directory is deleted : " + file.getAbsolutePath());
                }
            }

        } else {
            //if file, then delete it
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }

    public static String read(String file) {

        BufferedReader br = null;

        try {

            String sCurrentLine;
            StringBuffer buffer = new StringBuffer();

            br = new BufferedReader(new FileReader(file));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);

                buffer.append(sCurrentLine);

            }
            return (buffer.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return "";
    }

}