Example usage for java.io OutputStream close

List of usage examples for java.io OutputStream close

Introduction

In this page you can find the example usage for java.io OutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with this stream.

Usage

From source file:Main.java

public static void copyFile(File src, File desc) throws IOException {
    InputStream is = null;//from  ww w  .j  av  a  2  s. co  m
    OutputStream os = null;
    try {
        is = new FileInputStream(src);
        os = new FileOutputStream(desc);
        copyStream(is, os);
    } finally {
        if (is != null)
            is.close();
        if (os != null)
            os.close();
    }
}

From source file:fr.paris.lutece.plugins.directory.web.DoDownloadFile.java

/**
 * Write in the http response the file to upload
 * @param request the http request//from  w w w.ja v  a 2 s  .c  om
 * @param response The http response
 * @return Error Message
 *
 */
public static String doDownloadFile(HttpServletRequest request, HttpServletResponse response) {
    Plugin plugin = PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME);
    String strIdFile = request.getParameter(PARAMETER_ID_FILE);
    int nIdFile = DirectoryUtils.CONSTANT_ID_NULL;

    if (StringUtils.isBlank(strIdFile) || !StringUtils.isNumeric(strIdFile)) {
        String strIdDirectoryRecord = request.getParameter(DirectoryUtils.PARAMETER_ID_DIRECTORY_RECORD);
        String strIdEntry = request.getParameter(DirectoryUtils.PARAMETER_ID_ENTRY);

        if ((StringUtils.isBlank(strIdDirectoryRecord) || !StringUtils.isNumeric(strIdDirectoryRecord))
                && (StringUtils.isBlank(strIdEntry) || !StringUtils.isNumeric(strIdEntry))) {
            return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_DURING_DOWNLOAD_FILE,
                    AdminMessage.TYPE_STOP);
        }

        int nIdDirectoryRecord = DirectoryUtils.convertStringToInt(strIdDirectoryRecord);
        int nIdEntry = DirectoryUtils.convertStringToInt(strIdEntry);
        RecordFieldFilter rfFilter = new RecordFieldFilter();
        rfFilter.setIdRecord(nIdDirectoryRecord);
        rfFilter.setIdEntry(nIdEntry);

        List<RecordField> listRecordFields = RecordFieldHome.getRecordFieldList(rfFilter, plugin);

        if ((listRecordFields != null) && !listRecordFields.isEmpty()) {
            RecordField recordField = listRecordFields.get(0);

            if ((recordField != null) && (recordField.getFile() != null)) {
                nIdFile = recordField.getFile().getIdFile();
            }
        }

        if ((nIdFile == DirectoryUtils.CONSTANT_ID_NULL) || (nIdFile == DirectoryUtils.CONSTANT_ID_ZERO)) {
            return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_DURING_DOWNLOAD_FILE,
                    AdminMessage.TYPE_STOP);
        }
    } else {
        nIdFile = DirectoryUtils.convertStringToInt(strIdFile);
    }

    File file = FileHome.findByPrimaryKey(nIdFile, plugin);
    PhysicalFile physicalFile = (file != null)
            ? PhysicalFileHome.findByPrimaryKey(file.getPhysicalFile().getIdPhysicalFile(), plugin)
            : null;

    if (physicalFile != null) {
        try {
            byte[] byteFileOutPut = physicalFile.getValue();
            DirectoryUtils.addHeaderResponse(request, response, file.getTitle());

            String strMimeType = file.getMimeType();

            if (strMimeType == null) {
                strMimeType = FileSystemUtil.getMIMEType(file.getTitle());
            }

            response.setContentType(strMimeType);
            response.setContentLength(byteFileOutPut.length);

            OutputStream os = response.getOutputStream();
            os.write(byteFileOutPut);
            os.close();
        } catch (IOException e) {
            AppLogService.error(e);
        }
    }

    return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_DURING_DOWNLOAD_FILE,
            AdminMessage.TYPE_STOP);
}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * /*from w w w.  j  ava  2 s.com*/
 * 
 * @param path
 * @param fileName
 * @param response
 * @return
 */
public static void download(String path, String fileName, HttpServletResponse response) {
    try {

        if (StringUtils.isEmpty(path)) {
            throw new IllegalArgumentException("?");
        } else {
            File file = new File(path);
            if (!file.exists()) {
                throw new IllegalArgumentException("??");
            }
        }
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("???");
        }
        if (response == null) {
            throw new IllegalArgumentException("response ?");
        }

        // path
        File file = new File(path);

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.tc.process.Exec.java

private static void closeQuietly(OutputStream output) {
    if (output != null) {
        try {// www.  j  av a 2 s  . c  om
            output.close();
        } catch (IOException ioe) {
            // quiet
        }
    }
}

From source file:Main.java

public static void copyStream(InputStream in, OutputStream out) {
    try {//w w  w  .  jav a 2s  .  co m
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Base64.java

private static void writeBytes(File file, byte[] data) {
    try {//  w ww .  j a va 2 s .  c  o  m
        OutputStream fos = new FileOutputStream(file);
        OutputStream os = new BufferedOutputStream(fos);
        os.write(data);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Copy a uri file to indicated file path
 * //  www.ja v a 2s .  c om
 * @param context   the application context
 * @param uri       the uri file to copy
 * @param dest      the dest file 
 * @throws IOException
 */
public static void copyUriTo(Context context, Uri uri, File dest) throws IOException {
    InputStream input = null;
    OutputStream output = null;

    try {
        input = context.getContentResolver().openInputStream(uri);
        output = new FileOutputStream(dest);

        copyFileUsingStream(input, output);
    } finally {
        input.close();
        output.close();
    }
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

public static void unTar(File inFile, File untarDir) throws IOException, ArchiveException {

    final InputStream is = new FileInputStream(inFile);
    final TarArchiveInputStream in = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream(ArchiveStreamFactory.TAR, is);
    TarArchiveEntry entry = null;/*from  ww  w . j a  v  a  2s.co m*/
    untarDir.mkdirs();
    while ((entry = (TarArchiveEntry) in.getNextEntry()) != null) {
        byte[] content = new byte[(int) entry.getSize()];
        in.read(content);
        final File entryFile = new File(untarDir, entry.getName());
        if (entry.isDirectory() && !entryFile.exists()) {
            if (!entryFile.mkdirs()) {
                throw new IOException("Create directory failed: " + entryFile.getAbsolutePath());
            }
        } else {
            final OutputStream out = new FileOutputStream(entryFile);
            IOUtils.write(content, out);
            out.close();
        }
    }
    in.close();
}

From source file:cn.zhuqi.mavenssh.web.util.test.FtpTest.java

/**
 * Description: FTP?/*  ww w  . j av  a 2  s .  c o  m*/
 *
 * @Version1.0
 * @param url FTP?hostname
 * @param port FTP??
 * @param username FTP?
 * @param password FTP?
 * @param remotePath FTP?
 * @param fileName ???
 * @param localPath ??
 * @return
 */
public static boolean downloadFile(String url, int port, String username, String password, String remotePath,
        String fileName, String localPath) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        // FTP?
        if (port > -1) {
            ftp.connect(url, port);
        } else {
            ftp.connect(url);
        }
        ftp.login(username, password);//
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(remotePath);//FTP?
        FTPFile[] fs = ftp.listFiles();
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                File localFile = new File(localPath + "/" + ff.getName());
                OutputStream is = new FileOutputStream(localFile);
                ftp.retrieveFile(ff.getName(), is);
                is.close();
            }
        }

        ftp.logout();
        success = true;
    } catch (IOException e) {
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
            }
        }
    }
    return success;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.SaveModelUtils.java

private static void copySingleFile(File source, File destination) throws IOException {
    InputStream inputstream = new FileInputStream(source);
    OutputStream outputstream = new FileOutputStream(destination);
    IOUtils.copy(inputstream, outputstream);
    inputstream.close();//  w w w.j a  v a2 s.c  o m
    outputstream.close();
}