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:es.urjc.mctwp.bbeans.research.image.DownloadBean.java

private void addFileToZos(ZipOutputStream zos, File file, String path) throws IOException {

    //Prepare entry path
    String entry = null;/*from   w  w  w  .j  av  a2  s .c  om*/
    if (path != null && !path.isEmpty())
        entry = path + "/" + file.getName();
    else
        entry = file.getName();

    //Create zip entry
    ZipEntry ze = new ZipEntry(entry);
    zos.putNextEntry(ze);

    //Write zip entry
    FileInputStream fileIS = new FileInputStream(file);
    while (fileIS.available() > 0) {
        byte bytes[] = new byte[fileIS.available()];
        fileIS.read(bytes);
        zos.write(bytes);
    }

    zos.flush();
    fileIS.close();
}

From source file:com.tzutalin.configio.JsonConfig.java

@Override
public boolean loadFromFile() {
    // If it has loaed to memory, return true directly
    if (mbLoadToMemory == true) {
        return true;
    }/*w  w  w  .  j  a v a  2  s. c om*/

    if (TextUtils.isEmpty(mTargetPath)) {
        throw new IllegalAccessError("Empty file path");
    }

    if (new File(mTargetPath).exists()) {
        try {
            File f = new File(mTargetPath);
            FileInputStream is = new FileInputStream(f);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            String response = new String(buffer);
            JSONObject jsonObj = new JSONObject(response);
            Map map = toMap(jsonObj);
            map.putAll(mMap);
            mMap = map;
            // Print log
            dumpMap();
            mbLoadToMemory = true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return mbLoadToMemory;
}

From source file:cn.org.once.cstack.cli.utils.FileUtils.java

public String uploadFile(File path) {
    checkConnectedAndInFileExplorer();/*  w w  w . j  a v  a 2 s.com*/

    File file = path;
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.available();
        fileInputStream.close();
        FileSystemResource resource = new FileSystemResource(file);
        Map<String, Object> params = new HashMap<>();
        params.put("file", resource);
        params.putAll(authentificationUtils.getMap());
        restUtils.sendPostForUpload(authentificationUtils.finalHost + "/file/container/" + currentContainerId
                + "/application/" + applicationUtils.getCurrentApplication().getName() + "?path=" + currentPath,
                params);
    } catch (IOException e) {
        log.log(Level.SEVERE, "File not found! Check the path file");
        statusCommand.setExitStatut(1);
    }
    return "File uploaded";
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

protected static void uploadFile(String locationFilename, String saveFilename) {
    System.out.println("saving " + locationFilename + "!! ");
    if (!saveFilename.contains("."))
        saveFilename = saveFilename + Utilities.getExtension(locationFilename);

    if (!fileExistsOnServer(saveFilename)) {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = locationFilename;
        String urlServer = "http://folk.ntnu.no/bjornava/upload/upload.php";
        //         String urlServer = "http://timelinegamified.appspot.com/upload.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;

        try {/*from  w w  w.  ja  va2s . c om*/
            FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + saveFilename + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            System.out.println("Server response: " + serverResponseCode + " Message: " + serverResponseMessage);
        } catch (Exception ex) {
            //Exception handling
        }
    } else {
        System.out.println("image exists on server");
    }
}

From source file:com.all.rds.service.impl.ChunksFSStorageService.java

private byte[] readChunk(String trackId, int chunkNumber) throws IOException {
    File chunkFile = getChunkFile(trackId, chunkNumber);
    FileInputStream fis = new FileInputStream(chunkFile);
    byte[] chunk = new byte[fis.available()];
    fis.read(chunk);/*from w  ww .j  a v a2  s  .  c o m*/
    fis.close();
    return chunk;
}

From source file:com.gst.infrastructure.documentmanagement.data.ImageData.java

public boolean available() {
    int available = -1; // not -1
    if (this.storageType.equals(StorageType.S3.getValue()) && this.inputStream != null) {
        try {/*from w  w  w.  j  a va2 s .co  m*/
            available = this.inputStream.available();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    } else if (this.storageType.equals(StorageType.FILE_SYSTEM.getValue()) && this.file != null) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(this.file);
            available = fileInputStream.available();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return available >= 0;
}

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

public static PrivateKey readKey(Context context) throws Exception {

    String keyFile = "privateKey.key";
    FileInputStream fis = context.openFileInput(keyFile);
    int kl = fis.available();
    byte[] kb = new byte[kl];
    fis.read(kb);//from ww  w. j  a  va 2 s. c  o  m
    fis.close();
    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(kb);
    PrivateKey pk = kf.generatePrivate(ks);

    return pk;
}

From source file:com.epam.controllers.pages.graphviz.GraphViz.java

/**
 * It will call the external dot program, and return the image in
 * binary format./*from   w  ww.ja  v  a  2s .co m*/
 * @param dot Source of the graph (in dot language).
 * @param type Type of the output image to be produced, e.g.: gif, dot, fig, pdf, ps, svg, png.
 * @return The image of the graph in .gif format.
 */
private byte[] get_img_stream(File dot, String type) {
    File img;
    byte[] img_stream = null;

    try {
        img = File.createTempFile("graph_", "." + type, new File(GraphViz.TEMP_DIR));
        Runtime rt = Runtime.getRuntime();

        // patch by Mike Chenault
        String[] args = { DOT, "-T" + type, dot.getAbsolutePath(), "-o", img.getAbsolutePath() };
        Process p = rt.exec(args);

        p.waitFor();

        FileInputStream in = new FileInputStream(img.getAbsolutePath());
        img_stream = new byte[in.available()];
        in.read(img_stream);
        // Close it if we need to
        if (in != null)
            in.close();

        if (img.delete() == false)
            log.warn("Warning: " + img.getAbsolutePath() + " could not be deleted!");
    } catch (java.io.IOException ioe) {
        log.warn("Error:    in I/O processing of tempfile in dir " + GraphViz.TEMP_DIR + "\n");
        log.warn("       or in calling external command");
        log.error("stacktrace", ioe);
    } catch (java.lang.InterruptedException ie) {
        log.error("Error: the execution of the external program was interrupted", ie);
    }

    return img_stream;
}

From source file:net.itransformers.idiscover.v2.core.discovererIntegrationTest.mplsLab.IntegrationTestJuniperOlive.java

@Before
public void setUp() throws Exception {

    File IntegrationTestJuniperOlive = new File(baseDir + File.separator
            + "iDiscover/netDiscoverer/src/test/resources/test/IntegrationTestJuniperOlive");
    if (IntegrationTestJuniperOlive.exists()) {
        try {/*from  ww w.j  a va 2s.  c  o  m*/
            FileUtils.deleteDirectory(new File(baseDir + File.separator
                    + "iDiscover/netDiscoverer/src/test/resources/test/IntegrationTestJuniperOlive"));
        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }

    XmlDiscoveryHelperFactory discoveryHelperFactory = null;
    try {
        Map<String, String> params1 = new HashMap<String, String>();
        params1.put("fileName",
                new File(baseDir, "iDiscover/conf/xml/discoveryParameters.xml").getAbsolutePath());
        discoveryHelperFactory = new XmlDiscoveryHelperFactory(params1);
    } catch (JAXBException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    try {
        Map<String, String> params1 = new HashMap<String, String>();
        String baseDir = (String) System.getProperties().get("basedir");
        params1.put("fileName",
                new File(baseDir, "iDiscover/conf/xml/discoveryParameters.xml").getAbsolutePath());
        discoveryHelperFactory = new XmlDiscoveryHelperFactory(params1);
    } catch (JAXBException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    discoveryTypes[0] = DiscoveryTypes.ADDITIONAL;
    Map<String, String> resourceParams = new HashMap<String, String>();
    resourceParams.put("community", "netTransformer-r");
    resourceParams.put("community2", "netTransformer-rw");
    resourceParams.put("version", "1");
    resourceParams.put("mibDir", "snmptoolkit/mibs");
    //        resource = new Resource("R1", "10.17.1.13", resourceParams);
    //        resource.setDeviceType("JUNIPER");
    discoveryHelper = discoveryHelperFactory.createDiscoveryHelper("JUNIPER");

    Map<String, String> params1 = new HashMap<String, String>();
    params1.put("path", "iDiscover/netDiscoverer/src/test/resources/test");
    params1.put("device-data-logging-path", "device-hierarchical");
    params1.put("raw-data-logging-path", "raw-data");
    params1.put("device-centric-logging-path", "device-centric");
    params1.put("network-centric-logging-path", "undirected");
    // params1.put("xslt","iDiscover/conf/xslt/transformator-undirected2.xslt");

    //        deviceLogger = new DeviceFileLogger(params1,new File(baseDir),"IntegrationTestJuniperOlive");
    //   xmlTopologyDeviceLogger = new XmlTopologyDeviceLogger(params1,new File(baseDir),"IntegrationTestJuniperOlive");

    FileInputStream is = new FileInputStream(
            "iDiscover/netDiscoverer/src/test/resources/raw-data-juniper-olive.xml");
    byte[] data = new byte[is.available()];
    is.read(data);
    rawdata.setData(data);
}

From source file:sd.code.stagent.fileservices.BackupFiles.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//  w w w  .  ja  v  a2s  . com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String requestText = Web.readClient(request);
    try {

        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(requestText);
        String dir = obj.get("directory").toString();
        String ext = obj.get("ext").toString();
        String backupName = obj.get("name").toString();

        String compressedFileName = "/tmp/pbx-" + Math.random() + ".zip";

        boolean success = compressFiles(dir, compressedFileName, ext);

        JSONObject result = new JSONObject();
        if (!success) {
            result.put("success", false);
            result.put("errorcode", 1);
            result.put("message", lastError);
            PrintWriter out = response.getWriter();
            out.println(result.toJSONString());
        }

        OutputStream servletOut = response.getOutputStream();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=" + backupName + ".zip");

        FileInputStream stream = new FileInputStream(compressedFileName);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(stream);
        response.setContentLength(stream.available());

        byte data[] = new byte[10024];
        int len;
        while ((len = bufferedInputStream.read(data)) != -1) {
            servletOut.write(data, 0, len);
        }

        bufferedInputStream.close();
        stream.close();

    } catch (Exception ex) {
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        result.put("success", false);
        result.put("errorcode", 5);
        result.put("message", ex.toString());

        out.println(result.toJSONString());
    }

}