Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:com.dien.upload.server.UploadShpServlet.java

/**
 * Override executeAction to save the received files in a custom place and delete this items from session.
 *//*from   ww w . j  av  a  2  s.  c  om*/
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    JSONObject obj = new JSONObject();
    HttpSession session = request.getSession();
    User users = (User) session.getAttribute("user");
    if (users != null && users.isDataAuth()) {

        for (FileItem item : sessionFiles) {
            if (false == item.isFormField()) {

                try {
                    // 1. ?
                    File file = File.createTempFile(item.getFieldName(), ".zip");
                    item.write(file);
                    FileInputStream fis = new FileInputStream(file);
                    if (fis.available() > 0) {
                        System.out.println("File has " + fis.available() + " bytes");
                        // 2.zip
                        CopyFile copyFile = new CopyFile();

                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        //
                        String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName() + "_"
                                + df.format(new Date()) + "_" + new Random().nextInt(1000);
                        copyFile.delFolder(tmpFolder);
                        copyFile.newFolder(tmpFolder);
                        ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true);
                        // 3.???shp
                        ArrayList<String> slist = new ArrayList<String>();
                        getAllFile(new File(tmpFolder), slist);
                        if (slist.size() > 0) {
                            ArrayList<String> msglist = new ArrayList<String>();
                            if (checkShpFileComplete(slist.get(0), msglist)) {
                                // 4. shp
                                // SDEWrapper sde = new SDEWrapper(Config.getProperties());
                                File shpFile = new File(slist.get(0));
                                String path = shpFile.getPath();
                                String layerName = shpFile.getName();
                                layerName = layerName.substring(0, layerName.indexOf("."));
                                // ???
                                // ??
                                layerName = basis.generatorTableName(layerName);
                                session.setAttribute(layerName, path);
                                // sde.shpToSde(path, layerName);
                                // 5. ?
                                // logger.info("--" + file.getAbsolutePath() + "--isexist: "+ file.exists());

                                // / Save a list with the received files
                                receivedFiles.put(item.getFieldName(), file);
                                receivedContentTypes.put(item.getFieldName(), item.getContentType());

                                /// Compose a xml message with the full file information
                                obj.put("fieldname", item.getFieldName());
                                obj.put("name", item.getName());
                                obj.put("size", item.getSize());
                                obj.put("type", item.getContentType());
                                obj.put("layerName", layerName);
                                obj.put("ret", true);
                                obj.put("msg", "??");

                            } else {
                                obj.put("ret", false);
                                obj.put("msg", Util.listToWhere(msglist, ","));
                            }
                        } else {
                            obj.put("ret", false);
                            obj.put("msg", "zipshp");
                        }
                    } else {
                        obj.put("ret", false);
                        obj.put("msg", "?");
                    }
                } catch (IOException e) {
                    obj.put("ret", false);
                    obj.put("msg", "shpshp?????");
                } catch (InterruptedException e) {
                    obj.put("ret", false);
                    obj.put("msg", "??");
                } catch (Exception e) {
                    obj.put("ret", false);
                    obj.put("msg", "??");
                }
            }
        }
    } else {
        obj.put("msg", "??");
    }
    removeSessionFileItems(request);
    return obj.toString();
}

From source file:org.apache.drill.exec.client.DumpCat.java

/**
 * Batch mode://from   w  w  w.  j  a  va  2  s  .  c  o  m
 * $drill-dumpcat --file=local:///tmp/drilltrace/[queryid]_[tag]_[majorid]_[minor]_[operator] --batch=123 --include-headers=true
 * Records: 1/1
 * Average Record Size: 8 bytes
 * Total Data Size: 8 bytes
 * Schema Information
 * name: col1, minor_type: int4, data_mode: nullable
 * name: col2, minor_type: int4, data_mode: non-nullable
 * @param targetBatchNum
 * @throws Exception
 */
protected void doBatch(FileInputStream input, int targetBatchNum, boolean showHeader) throws Exception {
    int batchNum = -1;

    VectorAccessibleSerializable vcSerializable = null;

    while (input.available() > 0 && batchNum++ < targetBatchNum) {
        vcSerializable = new VectorAccessibleSerializable(DumpCat.allocator);
        vcSerializable.readFromStream(input);

        if (batchNum != targetBatchNum) {
            VectorContainer vectorContainer = (VectorContainer) vcSerializable.get();
            vectorContainer.zeroVectors();
        }
    }

    if (batchNum < targetBatchNum) {
        System.out.println(String.format(
                "Wrong input of batch # ! Total # of batch in the file is %d. Please input a number 0..%d as batch #",
                batchNum + 1, batchNum));
        input.close();
        System.exit(-1);
    }

    if (vcSerializable != null) {
        showSingleBatch(vcSerializable, showHeader);
        VectorContainer vectorContainer = (VectorContainer) vcSerializable.get();
        vectorContainer.zeroVectors();
    }
}

From source file:org.eclipse.xtend.typesystem.xsd.tests.AbstractTestCase.java

protected void assertFileContents(String file, String expectedContent) {
    try {/* w  w  w.  ja  v  a  2s.  c  o m*/
        File f = new File(getSrcGenDir() + "/" + file);
        assertTrue(f.isFile());
        FileInputStream fs = new FileInputStream(f);
        byte b[] = new byte[fs.available()];
        fs.read(b);
        assertEquals(expectedContent, new String(b));
    } catch (IOException e) {
        fail(e.getMessage());
    }
}

From source file:com.upyun.sdk.UpYunClient.java

public void uploadFile(File file) throws UpYunExcetion {
    FileInputStream fis = null;
    try {//  w w  w  .  j ava 2 s  .  c  o  m
        fis = new FileInputStream(file);
        uploadFile(file.getName(), fis, fis.available());
    } catch (FileNotFoundException e) {
        LogUtil.exception(logger, e);
    } catch (IOException e) {
        LogUtil.exception(logger, e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                LogUtil.exception(logger, e);
            }
        }
    }
}

From source file:com.dien.manager.servlet.UploadShpServlet.java

/**
 * Override executeAction to save the received files in a custom place and delete this items from session.
 *//*from   w w w  .  j  a  v  a2 s  . c  o m*/
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    String response = "";
    int cont = 0;
    HttpSession session = request.getSession();
    User users = (User) session.getAttribute("user");
    if (users != null && users.isDataAuth()) {

        for (FileItem item : sessionFiles) {
            if (false == item.isFormField()) {
                cont++;
                try {
                    // 1. ?
                    File file = File.createTempFile(item.getFieldName(), ".zip");
                    item.write(file);
                    FileInputStream fis = new FileInputStream(file);
                    if (fis.available() > 0) {
                        System.out.println("File has " + fis.available() + " bytes");
                        // 2.zip
                        CopyFile copyFile = new CopyFile();
                        String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName();
                        copyFile.delFolder(tmpFolder);
                        copyFile.newFolder(tmpFolder);
                        ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true);
                        // 3.???shp
                        ArrayList<String> slist = new ArrayList<String>();
                        getAllFile(new File(tmpFolder), slist);
                        if (slist.size() > 0) {
                            ArrayList<String> msglist = new ArrayList<String>();
                            if (checkShpFileComplete(slist.get(0), msglist)) {
                                // 4. shp
                                // SDEWrapper sde = new SDEWrapper(Config.getProperties());
                                File shpFile = new File(slist.get(0));
                                String path = shpFile.getPath();
                                String layerName = shpFile.getName();
                                layerName = layerName.substring(0, layerName.indexOf("."));
                                // ???
                                // ??
                                layerName = basis.generatorTableName(layerName);
                                session.setAttribute(layerName, path);
                                // sde.shpToSde(path, layerName);
                                // 5. ?
                                logger.info("--" + file.getAbsolutePath() + "--isexist: " + file.exists());

                                // / Save a list with the received files
                                receivedFiles.put(item.getFieldName(), file);
                                receivedContentTypes.put(item.getFieldName(), item.getContentType());

                                // / Compose a xml message with the full file information
                                response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont
                                        + "-field>\n";
                                response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont
                                        + "-name>\n";
                                response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont
                                        + "-size>\n";
                                response += "<file-" + cont + "-type>" + item.getContentType() + "</file-"
                                        + cont + "type>\n";
                                response += "<file-" + cont + "-layerid>" + layerName + "</file-" + cont
                                        + "layerid>\n";
                            } else {
                                response += "<file-" + cont + "-error>" + Util.listToWhere(msglist, ",")
                                        + "</file-" + cont + "error>\n";
                            }
                        } else {
                            response += "<file-" + cont + "-error>zipshp</file-"
                                    + cont + "error>\n";
                        }
                    } else {
                        response += "<file-" + cont + "-error>?</file-" + cont
                                + "error>\n";
                    }
                } catch (IOException e) {
                    response += "<file-" + cont
                            + "-error>shpshp??????</file-"
                            + cont + "error>\n";

                } catch (InterruptedException e) {
                    response += "<file-" + cont + "-error>??</file-" + cont
                            + "error>\n";

                } catch (Exception e) {
                    response += "<file-" + cont
                            + "-error>???</file-" + cont
                            + "error>\n";

                }
            }
        }
    } else {
        response += "<file-" + cont + "-error>???</file-" + cont + "error>\n";
    }
    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send information of the received files to the client.
    return "<response>\n" + response + "</response>\n";
}

From source file:com.mhise.util.MHISEUtil.java

public static File addBeginEndCertificateTag(Context context, File certfile, String filePath) {
    File updatedFile = null;//w  ww.  j av  a2s.  c o  m
    java.security.cert.Certificate[] chain = {};

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        FileInputStream ins = new FileInputStream(certfile);
        chain = certificateFactory.generateCertificates(ins).toArray(chain);
        ins.close();

        updatedFile = certfile;
    } catch (CertificateException e) {
        // TODO: handle exception
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag", " CertificateException " + e);
        try {
            String TAG_BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n";
            String TAG_END_CERTIFICATE = "\n-----END CERTIFICATE-----";

            byte[] kb1 = TAG_BEGIN_CERTIFICATE.getBytes();
            byte[] kb3 = TAG_END_CERTIFICATE.getBytes();

            FileInputStream fis = new FileInputStream(certfile);
            int kl = fis.available();
            byte[] kb2 = new byte[kl];
            fis.read(kb2);
            fis.close();

            certfile.delete();
            updatedFile = new File(filePath);
            FileOutputStream fos = new FileOutputStream(filePath);

            ArrayList<byte[]> list = new ArrayList<byte[]>();
            list.add(kb1);
            list.add(kb2);
            list.add(kb3);
            concatenateByteArrays(list);
            fos.write(concatenateByteArrays(list));
            fos.close();

        } catch (IOException e1) {

            Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "Inside catch ->try " + e1);
            return null;
        }

        return updatedFile;
    }

    catch (FileNotFoundException e) {
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "FileNotFoundException " + e);
    } catch (IOException e) {
        Logger.debug("MHISEUtil-->addBeginEndCertificateTag ", "IOException " + e);
    }

    return updatedFile;
}

From source file:com.all.dht.util.DhtFileUtils.java

public byte[] readFromFileSystem(String primaryKey) {
    String filePath = createStoreDirectoryPath(primaryKey) + primaryKey;
    File file = new File(filePath);
    if (file.exists()) {
        FileInputStream fis;
        try {/*w  ww  .j a v  a  2s  .  c o m*/
            fis = new FileInputStream(file);
            byte[] oversizedValue = new byte[fis.available()];
            fis.read(oversizedValue);
            fis.close();
            return oversizedValue;
        } catch (IOException e) {
            LOG.error(e, e);
        }
    }
    return null;
}

From source file:com.naryx.tagfusion.cfm.tag.cfCONTENT.java

private void readFile(cfStructData attributes, cfSession _Session) throws cfmRunTimeException {
    // Create File object
    File thisFile;/*from   w ww  .jav a2  s  .com*/
    if (getDynamic(attributes, _Session, "URIDIRECTORY").getBoolean())
        thisFile = FileUtils.getRealFile(_Session.REQ, getDynamic(attributes, _Session, "FILE").getString());
    else
        thisFile = new File(getDynamic(attributes, _Session, "FILE").getString());

    if (!thisFile.exists())
        throw newRunTimeException("The file does not exist [" + thisFile + "]");

    try {
        // Open up the file
        FileInputStream in = new FileInputStream(thisFile);

        // Work out a reasonable sized buffer
        int filesize = in.available();
        int bufferSize = 8192; // default buffer size
        if (filesize >= 256000)
            bufferSize = 65536;
        else if (filesize >= 65536)
            bufferSize = 16384;

        byte[] buffer = new byte[bufferSize];
        int readCount = 0;
        while ((readCount = in.read(buffer)) != -1) {
            _Session.write(buffer, 0, readCount);
            _Session.pageFlush();
        }

        in.close();

    } catch (IOException E) {
        throw newRunTimeException(E.toString());
    }

    // Check to see if the file is to be deleted or not
    if (getDynamic(attributes, _Session, "DELETEFILE").getBoolean())
        thisFile.delete();
}

From source file:com.znsx.cms.service.impl.LicenseManagerImpl.java

/**
 * ??,?//from w  w w  .  j  av a2 s  .c  o  m
 * 
 * @return ?
 * @throws BusinessException
 * @author huangbuji
 *         <p />
 *         Create at 2014-2-12 ?5:42:36
 */
private byte[] getPublicBinKey() throws BusinessException {
    try {
        String path = LicenceUtil.class.getResource("").getPath();
        File publicFile = new File(path + "/binPublic.ky");
        FileInputStream fi = new FileInputStream(publicFile);
        byte[] publicKey = new byte[fi.available()];
        fi.read(publicKey);
        fi.close();
        return publicKey;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new BusinessException(ErrorCode.ERROR, "binPublic.ky not found !");
    } catch (IOException e) {
        e.printStackTrace();
        throw new BusinessException(ErrorCode.ERROR, "binPublic.ky read IOException !");
    }
}

From source file:net.ustyugov.jtalk.activity.vcard.SetVcardActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == IMAGE && data != null) {
            Uri uri = Uri.parse(data.getDataString());
            if (uri != null) {
                try {
                    FileInputStream fileInput = getContentResolver().openAssetFileDescriptor(uri, "r")
                            .createInputStream();
                    bytes = new byte[fileInput.available()];
                    fileInput.read(bytes);
                    Bitmap bm = Bitmap.createScaledBitmap(BitmapFactory.decodeFileDescriptor(fileInput.getFD()),
                            240, 240, true);
                    av.setImageBitmap(bm);
                    fileInput.close();//w  w w . j a v a  2s .  co  m
                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }
            }
        }
    }
}