Java Path File Name nio writeFileFromInputStream(String the_path, String the_filename, InputStream the_sis)

Here you can find the source of writeFileFromInputStream(String the_path, String the_filename, InputStream the_sis)

Description

Read raw bytes of a text stream and write the data to file specified by the filename.

License

Open Source License

Parameter

Parameter Description
the_path The directory where the file should be written.
the_filename The name which should be given to the uploaded file.
the_sis The InputStream which contains the file data.

Return

The number of bytes written. This number is negative if nonzero but an exception occurred.

Declaration

public static int writeFileFromInputStream(String the_path, String the_filename, InputStream the_sis) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.InvalidPathException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedInputStream;

import java.io.IOException;

public class Main {
    private static final int BUFFER = 32 * 1024;

    /**/*from   ww w  . ja va  2  s .c  o  m*/
    * Read raw bytes of a text stream and write the data to file specified by the filename.
    * @param the_path The directory where the file should be written.
    * @param the_filename The name which should be given to the uploaded file.
    * @param the_sis The InputStream which contains the file data.
    * @return The number of bytes written.  This number is negative if nonzero but an exception occurred.
    */
    public static int writeFileFromInputStream(String the_path, String the_filename, InputStream the_sis) {
        int byteswritten = 0;
        byte data[] = new byte[BUFFER];
        int count = 0;
        Path destpath = Paths.get(the_path + the_filename);
        try (OutputStream fos = Files.newOutputStream(destpath, StandardOpenOption.CREATE);
                BufferedInputStream bis = new BufferedInputStream(the_sis, BUFFER)) {
            data = new byte[BUFFER];
            count = 0;
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                fos.write(data, 0, count);
                byteswritten += count;
            }
        } catch (InvalidPathException ifex) {
            byteswritten = -byteswritten;
            ifex.printStackTrace();
        } catch (IOException ioex) {
            byteswritten = -byteswritten;
            ioex.printStackTrace();
        }
        return byteswritten;
    }
}

Related

  1. uploadFileToServer(InputStream input, String filename, String usercode, String basePath)
  2. validateDockerfilePath(String name)
  3. which(Path path, String name)
  4. writeDataFile(final String resourceName, final Path sourcePath)
  5. writeFile(String pathname, String data)