Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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;

public class Main {

    public static File copy(File in, String path, String name) {
        File newFile = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(in);
            newFile = writeFromInput(path, name, fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return newFile;
    }

    public static File writeFromInput(String path, String fileName, InputStream is) {
        File file = createFile(path, fileName);

        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int read = 0;
            while ((read = is.read(buffer)) != -1) {
                os.write(buffer, 0, read);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static File createFile(String path, String fileName) {
        return createFileOrDir(path, fileName, false);
    }

    private static File createFileOrDir(String path, String fileName, boolean isDir) {
        if (path.charAt(path.length() - 1) != '/') {
            path += '/';
        }

        File file = new File(path + fileName);
        if (!isDir) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            file.mkdir();
        }
        return file;
    }
}