Example usage for java.io FileOutputStream flush

List of usage examples for java.io FileOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.whatsthatlight.teamcity.hipchat.HipChatConfigurationController.java

public void saveConfiguration() throws IOException {
    XStream xstream = new XStream();
    xstream.processAnnotations(this.configuration.getClass());
    File file = new File(this.configFilePath);
    file.createNewFile();/*from  w  w  w .  jav  a  2  s  .c om*/
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    xstream.toXML(this.configuration, fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();
}

From source file:net.sf.jasperreports.pictonic.render.PictonicResourceHandler.java

private void writeBytesToFile(byte[] bytes, File dir, String fileName) {
    File resourceFile = new File(dir, fileName);
    if (log.isDebugEnabled()) {
        log.debug("creating file: " + resourceFile.getAbsolutePath());
    }//from   ww  w.java  2  s. c o  m
    FileOutputStream fos = null;
    try {
        if (resourceFile.createNewFile()) {
            fos = new FileOutputStream(resourceFile);
            fos.write(bytes);
            fos.flush();
        }
    } catch (IOException e) {
        throw new JRRuntimeException("unable to create file: " + resourceFile.getAbsolutePath(), e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                if (log.isWarnEnabled()) {
                    log.warn("failed to close file stream for file: " + resourceFile.getAbsolutePath(), e);
                }
            }
        }
    }
}

From source file:TextFileHandler.java

public void writeFile(File f, String inBody) {
    //  System.out.println("WRITING "+f);
    int size = (int) inBody.length();
    int bytesOut = 0;
    byte data[] = inBody.getBytes(); //new byte[size] ;
    //   data = body.getBytes();
    try {/*from  w w w  .  j ava  2  s.c o m*/
        FileOutputStream out = new FileOutputStream(f);
        out.write(data, 0, size);
        out.flush();
        out.close();
    } catch (IOException e) {
        System.out.println("Error: TextFileHandler couldn't write to " + fName + "\n");
    }
}

From source file:com.cats.version.deamon.HttpDownloadFiles.java

public boolean download(String url, String fileName) {
    try {/*from w  w w .  j  av a  2 s .  c om*/
        HttpClient client = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = client.execute(httpget);
        if (response.getStatusLine().getStatusCode() != 200) {
            lastError = "Error status code: " + response.getStatusLine().getStatusCode();
            return false;
        }
        Header[] headers = response.getHeaders("file_flag");
        if (headers == null || headers.length == 0 || !headers[0].getValue().equals("yes")) {
            lastError = "parse httpdown response header fail";
            return false;
        }
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        File file = new File(System.getProperty("user.dir") + File.separator + fileName);
        file.getParentFile().mkdirs();
        FileOutputStream fileout = new FileOutputStream(file);
        byte[] buffer = new byte[CACHE];
        int iLen = 0;
        while ((iLen = is.read(buffer)) != -1) {
            fileout.write(buffer, 0, iLen);
        }
        is.close();
        fileout.flush();
        fileout.close();
    } catch (Exception e) {
        e.printStackTrace();
        lastError = e.getMessage();
        return false;
    }
    return true;
}

From source file:de.devmil.muzei.bingimageofthedayartsource.cache.BingImageCache.java

/**
 * gets called when the download of an image is finished.
 * The image gets written to the storage
 * @param content/*from  w ww. j av  a2s .  c  o  m*/
 * @param tag
 */
@Override
public synchronized void downloadFinished(byte[] content, Object tag) {
    if (content != null) {
        Uri uri = (Uri) tag;
        String fName = getFileNameFromUri(uri);
        File f = new File(getCacheDirectory(), fName);
        try {
            if (f.exists())
                f.delete();
            FileOutputStream fOut = new FileOutputStream(f);
            fOut.write(content);
            fOut.flush();
            fOut.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:beans.UploadFilesBean.java

public void handleFileUpload(FileUploadEvent event) {
    FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, message);
    UploadedFile fileu = event.getFile();
    ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
    System.out.println(extContext.getRealPath("//WEB-INF//files//" + event.getFile().getFileName()));
    File result = new File(extContext.getRealPath("//WEB-INF//files//" + event.getFile().getFileName()));
    try {/*from ww w.j a  va2  s .c o  m*/
        InputStream iStream = fileu.getInputstream();
        FileOutputStream oStream = new FileOutputStream(result);
        byte[] buffer = new byte[BUFFER_SIZE];
        int bulk;
        while (true) {
            bulk = iStream.read(buffer);
            if (bulk < 0) {
                break;
            }
            oStream.write(buffer, 0, bulk);
            oStream.flush();
        }
        oStream.close();
        iStream.close();
        System.out.println("funciono supuestamente");

    } catch (IOException ex) {
        Logger.getLogger(UploadFilesBean.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("error culley");
    }

}

From source file:at.tuwien.minimee.migration.engines.MonitorEngineTOPDefault.java

/**
 * Copies resource file 'from' from destination 'to' and set execution permission.
 * /*  w  w w  . j a  v a 2s  .c om*/
 * @param from
 * @param to
 * @throws Exception
 */
protected void copyFile(String from, String to, String workingDirectory) throws Exception {

    //
    // copy the shell script to the working directory
    //
    URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from);
    File f = new File(monitorCallShellScriptUrl.getFile());
    String directoryPath = f.getAbsolutePath();
    // if the application was created as exploded archive, the absolute path is a real filename
    String fileName = from;
    InputStream in = null;
    if (directoryPath.indexOf(".jar!") > -1) {
        // this class is not in an exploded archive, extract the filename  
        URL urlJar = new URL(
                directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!')));

        JarFile jf = new JarFile(urlJar.getFile());
        JarEntry je = jf.getJarEntry(from);
        fileName = je.getName();
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    } else {
        in = new FileInputStream(f);
    }

    File outScriptFile = new File(to);

    FileOutputStream fos = new FileOutputStream(outScriptFile);
    int nextChar;
    while ((nextChar = in.read()) != -1)
        fos.write(nextChar);

    fos.flush();
    fos.close();

    //
    // This seems kind of hard core, but we have to set execution rights for the shell script, 
    // otherwise we wouldn't be allowed to execute it.
    // The Java-way with FilePermission didn't work for some reason.
    //
    try {
        LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor();
        cmdExecutor.setWorkingDirectory(workingDirectory);

        cmdExecutor.runCommand("chmod 777 " + to);
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.wudaosoft.net.httpclient.FileResponseHandler.java

@Override
public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();

    if (status != 200) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }// w w  w  . ja v a2  s. com

    HttpEntity entity = response.getEntity();

    if (entity == null || !entity.isStreaming()) {
        throw new ClientProtocolException("Response contains no content");
    }

    File tempFile = null;

    if (this.file != null) {
        tempFile = this.file;
    } else if (this.dir != null) {
        Header contentDisposition = response.getLastHeader("Content-disposition");
        String filename = contentDisposition.getValue().split(";")[1].split("=")[1].replace("\"", "");
        tempFile = new File(this.dir, filename);
    }

    Args.notNull(tempFile, "file");
    Args.check(tempFile.canWrite(), "file must be writeable");

    InputStream inputStream = entity.getContent();
    FileOutputStream outputStream = new FileOutputStream(tempFile);

    try {

        byte[] buff = new byte[4096];
        int size = -1;
        while ((size = inputStream.read(buff)) != -1) {

            outputStream.write(buff, 0, size);
        }

        outputStream.flush();

        return tempFile;
    } finally {
        try {
            outputStream.close();
        } catch (IOException e) {
        }
    }

}

From source file:com.rastating.droidbeard.net.SickbeardAsyncTask.java

protected Bitmap getShowBanner(long tvdbid, int cachedInSB) {
    Bitmap banner;/*  w w  w.  j a  v  a 2  s  . c  o m*/
    File cachedBanner = new File(getContext().getCacheDir(), String.valueOf(tvdbid) + ".png");
    if (cachedBanner.exists() && !cachedBanner.isDirectory()) {
        banner = BitmapFactory.decodeFile(cachedBanner.getAbsolutePath());
    } else {
        ArrayList<Pair<String, Object>> params = new ArrayList<Pair<String, Object>>();
        params.add(new Pair<String, Object>("tvdbid", tvdbid));
        banner = getBitmap("show.getbanner", params);

        if (cachedInSB == 1) {
            if (banner != null) {
                try {
                    FileOutputStream stream = new FileOutputStream(cachedBanner);
                    banner.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    stream.flush();
                    stream.close();
                } catch (Exception e) {
                    banner = getDefaultBanner();
                }
            }
        }

        if (banner == null) {
            banner = getDefaultBanner();
        }
    }

    return banner;
}

From source file:ru.develgame.jflickrorganizer.Threads.BackupRunnable.java

private void downloadPhoto(File newFile, Size size, PhotosInterface photoInt)
        throws FileNotFoundException, IOException, FlickrException {
    if (!newFile.exists()) {
        BufferedInputStream inStream = new BufferedInputStream(photoInt.getImageAsStream(size));

        FileOutputStream fos = new FileOutputStream(newFile);

        byte buffer[] = IOUtils.toByteArray(inStream);
        fos.write(buffer);//  w  w w . j  a  v a  2  s. co m

        fos.flush();
        fos.close();
        inStream.close();
    }
}