Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

In this page you can find the example usage for java.io BufferedOutputStream flush.

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:ftpserver.Data.java

public void sendFile(String file) throws Exception {
    isStop = false;/*  w w w  .j  a  v  a2  s. c om*/
    if (socket == null)
        throw new IOException("No client connected");
    String input = "";
    int i = 0;
    FileInputStream fin = null;
    BufferedOutputStream out = null;
    try {
        out = new BufferedOutputStream(socket.getOutputStream());
        fin = new FileInputStream(file);
        /*
        if(data.type == 'A') {
           PrintWriter rout=new PrintWriter(out);
           BufferedReader br = new BufferedReader(new InputStreamReader(fin));
           while(true) {
              input = br.readLine();
              if(input==null)
          break;
              rout.
           }
           rout.flush();
           //rout.close();
        } else {
                   
        }*/
        while (true) {
            i = fin.read();
            if (i == -1 || isStop == true) //if aborted
                break;
            out.write(i);
        }
        out.flush();
    } catch (Exception e) {
        throw e;
    } finally {
        if (fin != null)
            fin.close();
    }
}

From source file:net.ytbolg.mcxa.ForgeCheck.java

public String downloadFile(String remoteFilePath) throws IOException {

    URL urlfile = null;//from  w  ww.j a  va2 s.c  o  m
    HttpURLConnection httpUrl = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    File f = new File(GameInfo.Rundir + GameInfo.tpf + "temp.tmp");
    File xxxx = new File(f.getParent());
    xxxx.mkdirs();

    //      f.mkdirs();
    try {
        urlfile = new URL(remoteFilePath);
        httpUrl = (HttpURLConnection) urlfile.openConnection();
        httpUrl.connect();
        bis = new BufferedInputStream(httpUrl.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(f));
        int len = 2048;
        byte[] b = new byte[len];
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        bos.flush();
        bis.close();
        httpUrl.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String x = ReadFile(GameInfo.Rundir + GameInfo.tpf + "temp.tmp");
    f.delete();
    return x;
}

From source file:org.deeplearning4j.scaleout.statetracker.hazelcast.BaseHazelCastStateTracker.java

/**
 * Starts the rest api/* w ww  .  ja v  a  2s. co  m*/
 */
@Override
public void startRestApi() {
    String startApi = System.getProperty("startapi", "false");
    Boolean b = Boolean.parseBoolean(startApi);
    if (!b)
        return;
    try {
        if (PortTaken.portTaken(8080) || PortTaken.portTaken(8180)) {
            log.warn("Port taken for rest api");
            return;
        }
        InputStream is = new ClassPathResource("/hazelcast/dropwizard.yml").getInputStream();

        resource = new StateTrackerDropWizardResource(this);
        File tmpConfig = new File("hazelcast/dropwizard.yml");
        if (!tmpConfig.getParentFile().exists())
            tmpConfig.getParentFile().mkdirs();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpConfig));
        IOUtils.copy(is, bos);
        bos.flush();

        resource.run("server", tmpConfig.getAbsolutePath());
        tmpConfig.deleteOnExit();
    }

    catch (Error e1) {
        log.warn("Unable to start server", e1);

    } catch (Exception e) {
        log.warn("Unable to start server", e);
    }

}

From source file:com.amazonaws.eclipse.elasticbeanstalk.git.AWSGitPushCommand.java

private void extractZipFile(File zipFile, File destination) throws IOException {
    int BUFFER = 2048;

    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    BufferedOutputStream dest = null;
    try {/*from   w  ww .  j  a v a2  s.  c o m*/
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk

            if (entry.isDirectory())
                continue;

            File entryFile = new File(destination, entry.getName());
            if (!entryFile.getParentFile().exists()) {
                entryFile.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(entryFile);
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
        }
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(dest);
    }
}

From source file:eu.optimis.ics.ImageCreationServiceREST.java

/**
 * Uncompresses the given zip file. Unfortunately, the files' permission is not
 * preserved, especially with regards to an executable file.
 * @param zipFile       the zip file/*w  w  w. jav  a2s . c  o m*/
 * @param destination   the directory location
 * @throws IOException  IO Exception
 */
private void unzipFile(File zipFile, String destination) throws IOException {
    LOGGER.debug("ics.REST.unzipFile(): Unzipping " + zipFile + " to directory " + destination);
    //LOGGER.debug("ics.REST.unzipFile(): Opening input streams");
    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    File destinationDirectory = new File(destination);

    while ((entry = zin.getNextEntry()) != null) {
        //LOGGER.debug("ics.REST.unzipFile(): Extracting: " + entry);

        if (entry.isDirectory()) {
            //LOGGER.debug("ics.REST.unzipFile(): Directory found, will be created");
            File targetDirectory = new File(destinationDirectory, entry.getName());
            targetDirectory.mkdir();
        } else {
            // extract data
            // open output streams
            int BUFFER = 2048;

            File destinationFile = new File(destinationDirectory, entry.getName());
            destinationFile.getParentFile().mkdirs();

            //LOGGER.debug("ics.REST.unzipFile(): Creating parent file of destination: "
            //        + destinationFile.getParent());
            //boolean parentDirectoriesCreated = destinationFile.getParentFile().mkdirs();                
            //LOGGER.debug("ics.REST.unzipFile(): Result of creating parents: "
            //        + parentDirectoriesCreated);

            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];

            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zin.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
    }

    LOGGER.debug("ics.REST.unzipFile(): Unzipping file is done");
    zin.close();
    fis.close();
}

From source file:net.ytbolg.mcxa.VersionCheck.java

/**
 * @param args the command line arguments
 *///from w  w w.  ja v  a 2 s. c o m
public String downloadFile(String remoteFilePath) throws IOException {

    URL urlfile = null;
    HttpURLConnection httpUrl = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    File f = new File(GameInfo.Rundir + GameInfo.tpf + "temp.tmp");
    File xxxx = new File(f.getParent());
    xxxx.mkdirs();

    //      f.mkdirs();
    try {
        urlfile = new URL(remoteFilePath);
        httpUrl = (HttpURLConnection) urlfile.openConnection();
        httpUrl.connect();
        bis = new BufferedInputStream(httpUrl.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(f));
        int len = 2048;
        byte[] b = new byte[len];
        while ((len = bis.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        bos.flush();
        bis.close();
        httpUrl.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String x = ReadFile(GameInfo.Rundir + GameInfo.tpf + "temp.tmp");
    f.delete();
    return x;
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ?? ??.//from   w  w w . j a va2  s  . c om
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void view(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);

    }
    response.setContentType(fileDTO.getContentType());

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ??  .//from   ww  w .j  a v a2s. c  om
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
protected void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String fileId = (String) paramMap.get("fileId");

    StringBuilder sb = new StringBuilder();

    FileDTO fileDTO;
    fileDTO = fileManager.selectFileByFileId(fileId);
    logger.debug("fileDTO: {}", fileDTO);

    String repositoryPath = fileDTO.getRepositoryPath();
    String uniqueFilename = fileDTO.getUniqueFilename();
    String realFilename = fileDTO.getRealFilename();
    InputStream inputStream = null;
    if (StringUtils.isNotEmpty(repositoryPath)) {
        // FILE_SYSTEM
        sb.setLength(0);
        sb.append(repositoryPath);
        if (!repositoryPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(uniqueFilename);
        File file = new File(sb.toString());
        inputStream = new FileInputStream(file);
    } else {
        // DATABASE
        byte[] bytes = new byte[] {};
        if (fileDTO.getFileSize() > 0) {
            bytes = fileDTO.getBytes();
        }
        inputStream = new ByteArrayInputStream(bytes);
    }

    // set response contenttype, header
    String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8");
    logger.debug("realFilename: {}", realFilename);
    logger.debug("encodedRealFilename: {}", encodedRealFilename);

    response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE);
    sb.setLength(0);
    if (request.getHeader(HttpRequestHeaderConstants.USER_AGENT).indexOf("MSIE5.5") > -1) {
        sb.append("filename=");
    } else {
        sb.append("attachment; filename=");
    }
    sb.append(encodedRealFilename);
    response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString());

    logger.debug("header: {}", sb.toString());
    logger.debug("character encoding: {}", response.getCharacterEncoding());
    logger.debug("content type: {}", response.getContentType());
    logger.debug("bufferSize: {}", response.getBufferSize());
    logger.debug("locale: {}", response.getLocale());

    BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
    int bytesRead;
    byte buffer[] = new byte[2048];
    while ((bytesRead = bufferdInputStream.read(buffer)) != -1) {
        bufferedOutputStream.write(buffer, 0, bytesRead);
    }
    // flush stream
    bufferedOutputStream.flush();

    // close stream
    inputStream.close();
    bufferdInputStream.close();
    servletOutputStream.close();
    bufferedOutputStream.close();
}

From source file:InstallJars.java

public void copyStream(URLConnection conn, String target) throws IOException {
    prepDirs(target, false);//ww  w  . j  a v  a  2s .c  o  m
    BufferedInputStream is = new BufferedInputStream(conn.getInputStream(), BLOCK_SIZE * BLOCK_COUNT);
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(target), BLOCK_SIZE * BLOCK_COUNT);
    byte[] buf = new byte[bufferSize];
    for (int size = is.read(buf), count = 0; size >= 0; size = is.read(buf), count++) {
        // if (count % 4 == 0) print(".");
        os.write(buf, 0, size);
    }
    os.flush();
    os.close();
    is.close();
}

From source file:com.primitive.library.task.DownloadTask.java

@Override
protected String doInBackground(Void... params) {
    File file = null;/*from ww w  .j  a v  a  2  s. co  m*/
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {
        cli.getParams().setParameter("http.connection.timeout", Long.valueOf(timeout));
        HttpResponse res = cli.execute(request);
        int rescode = res.getStatusLine().getStatusCode();

        if (rescode == HttpStatus.SC_OK) {
            int length = (int) res.getEntity().getContentLength();
            this.progress.setMax(length);
            byte[] buffer = new byte[buffer_size];
            file = new File(this.savePath);
            is = res.getEntity().getContent();
            bis = new BufferedInputStream(is, buffer_size);
            bos = new BufferedOutputStream(new FileOutputStream(file, false), buffer_size);
            for (int size = 0; -1 < (size = bis.read(buffer));) {
                bos.write(buffer);
                this.publishProgress(size);
            }
            bos.flush();
            return this.savePath;
        } else {
            switch (rescode) {
            case HttpStatus.SC_NOT_FOUND:
                break;
            case HttpStatus.SC_REQUEST_TIMEOUT:
                break;
            default:
                break;
            }
            return null;
        }

    } catch (Throwable ex) {
        Logger.err(ex);
        return null;
    } finally {
        Closeable[] closeables = new Closeable[] { bos, bis, is };
        for (Closeable close : closeables) {
            if (close != null) {
                try {
                    close.close();
                } catch (IOException ex) {
                    Logger.warm(ex);
                }
            }
        }
    }
}