Example usage for java.io FileInputStream read

List of usage examples for java.io FileInputStream read

Introduction

In this page you can find the example usage for java.io FileInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:Main.java

public static boolean copy(String srcFile, String dstFile) {
    FileInputStream fis = null;
    FileOutputStream fos = null;//from  w ww .j  a  v  a 2 s. c o  m
    try {

        File dst = new File(dstFile);
        if (!dst.getParentFile().exists()) {
            dst.getParentFile().mkdirs();
        }

        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(dstFile);

        byte[] buffer = new byte[1024];
        int len = 0;

        while ((len = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return true;
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Uploads the specified file to the community site. The return identifier
 * can be used later when composing other requests.
 * //from w  w w . j av a2 s .  c o m
 * @param httpclient
 *            the http client
 * @param attachment
 *            the file to attach
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the identifier of the file uploaded, <code>null</code> otherwise
 * @throws CommunityAPIException
 */
public static String uploadFile(CloseableHttpClient httpclient, File attachment, Cookie authCookie)
        throws CommunityAPIException {
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(attachment);
        byte fileContent[] = new byte[(int) attachment.length()];
        fin.read(fileContent);

        byte[] encodedFileContent = Base64.encodeBase64(fileContent);
        FileUploadRequest uploadReq = new FileUploadRequest(attachment.getName(), encodedFileContent);

        HttpPost fileuploadPOST = new HttpPost(CommunityConstants.FILE_UPLOAD_URL);
        EntityBuilder fileUploadEntity = EntityBuilder.create();
        fileUploadEntity.setText(uploadReq.getAsJSON());
        fileUploadEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        fileUploadEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        fileuploadPOST.setEntity(fileUploadEntity.build());

        CloseableHttpResponse resp = httpclient.execute(fileuploadPOST);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());

        if (HttpStatus.SC_OK == httpRetCode) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            String fid = jsonRoot.get("fid").asText(); //$NON-NLS-1$
            return fid;
        } else {
            CommunityAPIException ex = new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        }

    } catch (FileNotFoundException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_FileNotFoundError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_FileUploadError, e);
    } finally {
        IOUtils.closeQuietly(fin);
    }
}

From source file:Main.java

/** Writes a copy of a file.
 * //from  w  ww  . j a  va  2  s .c  om
 * @param src the file to copy
 * @param dst the location to write the new file
 * @throws IOException
 */
public synchronized static void copy(File src, File dst) throws IOException {
    if (b1 == null)
        b1 = new byte[4096];

    FileInputStream in = null;
    FileOutputStream out = null;
    try {
        in = new FileInputStream(src);
        dst.getParentFile().mkdirs();
        dst.createNewFile();
        out = new FileOutputStream(dst);
        int k = in.read(b1);
        while (k != -1) {
            out.write(b1, 0, k);
            k = in.read(b1);
        }
    } finally {
        try {
            in.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        try {
            out.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

From source file:Main.java

/**
 * Reads a file that is embedded in our application and writes it to the device storage
 * @param context/*ww w. java  2s.c  o m*/
 * @param file
 * @param assetFileDescriptor
 */
private static void saveFileToDevice(Context context, File file, AssetFileDescriptor assetFileDescriptor) {
    // The output stream is used to write the new file to the device storage
    FileOutputStream outputStream = null;
    // The input stream is used for reading the file that is embedded in our application
    FileInputStream inputStream = null;
    try {
        byte[] buffer = new byte[1024];
        // Create the input stream
        inputStream = (assetFileDescriptor != null) ? assetFileDescriptor.createInputStream() : null;
        // Create the output stream
        outputStream = new FileOutputStream(file, false);
        // Read the file into buffer
        int i = (inputStream != null) ? inputStream.read(buffer) : 0;
        // Continue writing and reading the file until we reach the end
        while (i != -1) {
            outputStream.write(buffer, 0, i);
            i = (inputStream != null) ? inputStream.read(buffer) : 0;
        }

        outputStream.flush();
    } catch (IOException io) {
        // Display a message to the user
        Toast toast = Toast.makeText(context, "Could not save the file", Toast.LENGTH_SHORT);
        toast.show();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                // We should really never get this far, but we might consider adding a
                // warning/log entry here...
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                // We should really never get this far, but we might consider adding a
                // warning/log entry here...
            }
        }
    }
}

From source file:gov.va.chir.tagline.dao.FileDao.java

private static void saveZipFile(final File zipFile, final File... inputFiles) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

    for (File file : inputFiles) {
        final ZipEntry entry = new ZipEntry(file.getName());
        zos.putNextEntry(entry);/* w  w  w  . ja va  2 s  .  c  om*/

        final FileInputStream in = new FileInputStream(file);
        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        in.close();
        zos.closeEntry();
    }

    zos.close();
}

From source file:importer.filters.CceFilter.java

static String readFile(String name) {
    try {/*from   w  w w. j ava 2  s  . c om*/
        File f = new File(name);
        FileInputStream fis = new FileInputStream(f);
        byte[] data = new byte[(int) f.length()];
        fis.read(data);
        return new String(data, "UTF-8");
    } catch (Exception e) {
        return "";
    }
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

/**
 * Calculates the SHA-1 hash for the file at the given path.
 * @param path the location of the file to hash
 * @return the SHA-1 checksum for the file
 * @throws MPTException if a stream cannot be opened to the file
 *///from ww w  . j a v  a2 s . c o m
public static String sha1(String path) throws MPTException {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        FileInputStream fis = new FileInputStream(path);
        byte[] dataBytes = new byte[1024];

        int nread;
        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        }
        fis.close();

        byte[] mdbytes = md.digest();

        StringBuilder sb = new StringBuilder();
        for (byte mdbyte : mdbytes) {
            String hex = Integer.toHexString(0xff & mdbyte);
            if (hex.length() == 1)
                sb.append('0');
            sb.append(hex);
        }
        return sb.toString();
    } catch (Exception ex) {
        if (Config.ENFORCE_CHECKSUM)
            throw new MPTException(ERROR_COLOR + "Failed to get checksum for local package " + ID_COLOR + path
                    + ERROR_COLOR + "!");
    }
    return null;
}

From source file:Main.java

public static String uploadFile(String path) {
    String sourceFileUri = path;/* ww  w  .j  a  v  a 2  s.c o m*/
    File file = new File(sourceFileUri);
    ByteArrayOutputStream objByteArrayOS = null;
    FileInputStream objFileIS = null;
    boolean isSuccess = false;
    String strAttachmentCoded = null;

    if (!file.isFile()) {
        Log.w(TAG, "Source File not exist :" + sourceFileUri);
    } else {
        try {
            objFileIS = new FileInputStream(file);
            objByteArrayOS = new ByteArrayOutputStream();
            byte[] byteBufferString = new byte[(int) file.length()];
            objFileIS.read(byteBufferString);

            byte[] byteBinaryData = Base64.encode(byteBufferString, Base64.DEFAULT);
            strAttachmentCoded = new String(byteBinaryData);

            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Upload file to server", "error: " + e.getMessage(), e);
        } finally {
            try {
                objByteArrayOS.close();
                objFileIS.close();
            } catch (IOException e) {
                Log.e(TAG, "Error : " + e.getMessage());
            }
        }
    }

    if (isSuccess) {
        return strAttachmentCoded;
    } else {
        return "No Picture";
    }
}

From source file:com.spstudio.common.image.ImageUtils.java

/**
 * ,?byte//from  w w w .  j a  v a 2 s.co m
 *
 * @return
 */
public static byte[] loadFile() {
    File file = new File("d:/touxiang.jpg");

    FileInputStream fis = null;
    ByteArrayOutputStream baos = null;
    byte[] data = null;

    try {
        fis = new FileInputStream(file);
        baos = new ByteArrayOutputStream((int) file.length());

        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        data = baos.toByteArray();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
                fis = null;
            }

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

    return data;
}

From source file:com.mc.printer.model.utils.ZipHelper.java

private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
    if (file.exists()) {
        if (file.isDirectory()) {//?
            parentPath += file.getName() + File.separator;
            File[] files = file.listFiles();
            for (File f : files) {
                writeZip(f, parentPath, zos);
            }//  www  .j  a v a2 s  .  c  o  m
        } else {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                ZipEntry ze = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(ze);
                byte[] content = new byte[1024];
                int len;
                while ((len = fis.read(content)) != -1) {
                    zos.write(content, 0, len);
                    zos.flush();
                }

            } catch (FileNotFoundException e) {
                log.error("create zip file failed.", e);
            } catch (IOException e) {
                log.error("create zip file failed.", e);
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException e) {
                    log.error("create zip file failed.", e);
                }
            }
        }
    }
}