Example usage for java.io FileOutputStream getFD

List of usage examples for java.io FileOutputStream getFD

Introduction

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

Prototype

public final FileDescriptor getFD() throws IOException 

Source Link

Document

Returns the file descriptor associated with this stream.

Usage

From source file:edu.usf.cutr.siri.util.SiriUtils.java

/**
 * Write the given object to Android internal storage for this app
 * /*from   w w  w  . ja va 2  s.c  om*/
 * @param object
 *            serializable object to be written to cache (ObjectReader,
 *            ObjectMapper, or XmlReader)
 * @return true if object was successfully written to cache, false if it was
 *         not
 */
private synchronized static boolean writeToCache(Serializable object) {

    FileOutputStream fileStream = null;
    ObjectOutputStream objectStream = null;
    String fileName = "";
    boolean success = false;

    try {
        if (object instanceof XmlMapper) {
            fileName = XML_MAPPER + CACHE_FILE_EXTENSION;
        } else if (object instanceof ObjectMapper) {
            // ObjectMapper check must come after XmlMapper check,
            // since XmlMapper is subclass of ObjectMapper
            fileName = OBJECT_MAPPER + CACHE_FILE_EXTENSION;
        } else if (object instanceof ObjectReader) {
            fileName = OBJECT_READER + CACHE_FILE_EXTENSION;
        }

        cacheWriteStartTime = System.nanoTime();
        fileStream = new FileOutputStream(fileName);
        objectStream = new ObjectOutputStream(fileStream);
        objectStream.writeObject(object);
        objectStream.flush();
        fileStream.getFD().sync();
        cacheWriteEndTime = System.nanoTime();
        success = true;

        // Get size of serialized object
        File file = new File(fileName);

        long fileSize = file.length();

        System.out.println("Wrote " + fileName + " to cache (" + fileSize + " bytes) in "
                + df.format(getLastCacheWriteTime() / 1000000.0) + " ms.");
    } catch (IOException e) {
        // Reset timestamps to show there was an error
        cacheWriteStartTime = 0;
        cacheWriteEndTime = 0;
        System.out.println("Couldn't write object to cache: " + e);
        e.printStackTrace();
    } finally {
        try {
            if (objectStream != null) {
                objectStream.close();
            }
            if (fileStream != null) {
                fileStream.close();
            }
        } catch (Exception e) {
            System.out.println("Error closing file connections: " + e);
        }
    }

    return success;
}

From source file:com.commonsware.android.downloader.Downloader.java

@Override
public void onHandleIntent(Intent i) {
    try {/*from   w  w w . j  av  a2  s . com*/
        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        root.mkdirs();

        File output = new File(root, i.getData().getLastPathSegment());

        if (output.exists()) {
            output.delete();
        }

        URL url = new URL(i.getData().toString());
        HttpURLConnection c = (HttpURLConnection) url.openConnection();

        FileOutputStream fos = new FileOutputStream(output.getPath());
        BufferedOutputStream out = new BufferedOutputStream(fos);

        try {
            InputStream in = c.getInputStream();
            byte[] buffer = new byte[8192];
            int len = 0;

            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }

            out.flush();
        } finally {
            fos.getFD().sync();
            out.close();
            c.disconnect();
        }

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(ACTION_COMPLETE));
    } catch (IOException e2) {
        Log.e(getClass().getName(), "Exception in download", e2);
    }
}

From source file:org.tinymediamanager.core.movie.tasks.MovieExtraImageFetcher.java

private void downloadExtraFanart() {
    List<String> fanarts = movie.getExtraFanarts();

    // do not create extrafanarts folder, if no extrafanarts are selected
    if (fanarts.size() == 0) {
        return;/*  ww  w  .j a  va2s  . c om*/
    }

    try {
        Path folder = movie.getPathNIO().resolve("extrafanart");
        if (Files.isDirectory(folder)) {
            Utils.deleteDirectoryRecursive(folder);
            movie.removeAllMediaFiles(MediaFileType.EXTRAFANART);
        }
        Files.createDirectory(folder);

        // fetch and store images
        for (int i = 0; i < fanarts.size(); i++) {
            String urlAsString = fanarts.get(i);
            String providedFiletype = FilenameUtils.getExtension(urlAsString);
            Url url = new Url(urlAsString);
            Path file = folder.resolve("fanart" + (i + 1) + "." + providedFiletype);
            FileOutputStream outputStream = new FileOutputStream(file.toFile());
            InputStream is = url.getInputStream();
            IOUtils.copy(is, outputStream);
            outputStream.flush();
            try {
                outputStream.getFD().sync(); // wait until file has been completely written
                // give it a few milliseconds
                Thread.sleep(150);
            } catch (Exception e) {
                // empty here -> just not let the thread crash
            }
            outputStream.close();

            is.close();
            MediaFile mf = new MediaFile(file, MediaFileType.EXTRAFANART);
            mf.gatherMediaInformation();
            movie.addToMediaFiles(mf);
        }
    } catch (InterruptedException e) {
        LOGGER.warn("interrupted download extrafanarts");
    } catch (IOException e) {
        LOGGER.warn("download extrafanarts", e);
    }
}

From source file:org.tinymediamanager.core.movie.tasks.MovieExtraImageFetcher.java

private void downloadArtwork(MediaFileType type, String basename) {
    String artworkUrl = movie.getArtworkUrl(type);
    if (StringUtils.isBlank(artworkUrl)) {
        return;// w ww  .j  a  va 2  s  .  c  o m
    }

    String filename = basename;
    if (!filename.isEmpty()) {
        filename += "-";
    }

    try {
        String oldFilename = movie.getArtworkFilename(type);
        // we are lucky and have chosen our enums wisely - except the discart :(
        if (type == MediaFileType.DISCART) {
            filename += "disc." + FilenameUtils.getExtension(artworkUrl);
        } else {
            filename += type.name().toLowerCase(Locale.ROOT) + "." + FilenameUtils.getExtension(artworkUrl);
        }
        movie.removeAllMediaFiles(type);

        // debug message
        LOGGER.debug("writing " + type + " " + filename);

        // fetch and store images
        Url url1 = new Url(artworkUrl);
        Path tempFile = movie.getPathNIO().resolve(filename + ".part");
        FileOutputStream outputStream = new FileOutputStream(tempFile.toFile());
        InputStream is = url1.getInputStream();
        IOUtils.copy(is, outputStream);
        outputStream.flush();
        try {
            outputStream.getFD().sync(); // wait until file has been completely written
            // give it a few milliseconds
            Thread.sleep(150);
        } catch (Exception e) {
            // empty here -> just not let the thread crash
        }
        outputStream.close();
        is.close();

        // has tmm been shut down?
        if (Thread.interrupted()) {
            return;
        }

        // check if the file has been downloaded
        if (!Files.exists(tempFile) || Files.size(tempFile) == 0) {
            throw new Exception("0byte file downloaded: " + filename);
        }

        // delete the old one if exisiting
        if (StringUtils.isNotBlank(oldFilename)) {
            Path oldFile = movie.getPathNIO().resolve(oldFilename);
            Utils.deleteFileSafely(oldFile);
        }

        // delete new destination if existing
        Path destinationFile = movie.getPathNIO().resolve(filename);
        Utils.deleteFileSafely(destinationFile);

        // move the temp file to the expected filename
        if (!Utils.moveFileSafe(tempFile, destinationFile)) {
            throw new Exception("renaming temp file failed: " + filename);
        }

        movie.setArtwork(destinationFile, type);
        movie.callbackForWrittenArtwork(MediaFileType.getMediaArtworkType(type));
        movie.saveToDb();
    } catch (Exception e) {
        if (e instanceof InterruptedException) {
            // only warning
            LOGGER.warn("interrupted image download");
        } else {
            LOGGER.error("fetch image: " + e.getMessage());
        }
        // remove temp file
        Path tempFile = movie.getPathNIO().resolve(filename + ".part");
        if (Files.exists(tempFile)) {
            Utils.deleteFileSafely(tempFile);
        }
    }
}

From source file:com.palantir.paxos.PaxosStateLogImpl.java

private void writeRoundInternal(long seq, V round) {
    String name = getFilenameFromSeq(seq);
    File tmpFile = new File(path, name + TMP_FILE_SUFFIX);

    // compute checksum hash
    byte[] bytes = round.persistToBytes();
    byte[] hash = Sha256Hash.computeHash(bytes).getBytes();
    PaxosPersistence.PaxosHeader header = PaxosPersistence.PaxosHeader.newBuilder()
            .setChecksum(ByteString.copyFrom(hash)).build();

    FileOutputStream fileOut = null;
    try {/* ww  w .  ja va2 s .com*/
        fileOut = new FileOutputStream(tmpFile);
        header.writeDelimitedTo(fileOut);
        CodedOutputStream out = CodedOutputStream.newInstance(fileOut);
        out.writeBytesNoTag(ByteString.copyFrom(bytes));
        out.flush();
        fileOut.getFD().sync();
        fileOut.close();
    } catch (IOException e) {
        log.error("problem writing paxos state", e);
        throw Throwables.throwUncheckedException(e);
    } finally {
        IOUtils.closeQuietly(fileOut);
    }

    // overwrite file with tmp
    File file = new File(path, name);
    tmpFile.renameTo(file);

    // update version
    seqToVersionMap.put(seq, round.getVersion());
}

From source file:com.commonsware.android.foredown.Downloader.java

@Override
public void onHandleIntent(Intent i) {
    try {//from   www. j a v a  2  s  .  com
        String filename = i.getData().getLastPathSegment();

        startForeground(FOREGROUND_ID, buildForegroundNotification(filename));

        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        root.mkdirs();

        File output = new File(root, filename);

        if (output.exists()) {
            output.delete();
        }

        URL url = new URL(i.getData().toString());
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        FileOutputStream fos = new FileOutputStream(output.getPath());
        BufferedOutputStream out = new BufferedOutputStream(fos);

        try {
            InputStream in = c.getInputStream();
            byte[] buffer = new byte[8192];
            int len = 0;

            while ((len = in.read(buffer)) >= 0) {
                out.write(buffer, 0, len);
            }

            out.flush();
        } finally {
            fos.getFD().sync();
            out.close();
            c.disconnect();
        }

        stopForeground(true);
        raiseNotification(i, output, null);
    } catch (IOException e2) {
        stopForeground(true);
        raiseNotification(i, null, e2);
    }
}

From source file:org.tinymediamanager.scraper.util.CachedUrl.java

/**
 * Cache.//ww  w .  java  2s .c  o m
 * 
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 * @throws InterruptedException
 */
private void cache() throws IOException, InterruptedException {
    LOGGER.debug("Caching Url: " + url);
    long sizeHttp = -1;
    // workaround for local files
    InputStream is = null;
    if (!url.startsWith("file:")) {
        Url u = new Url(url);
        u.addHeaders(headersRequest);
        is = u.getInputStream();
        sizeHttp = u.getContentLength();

        // also store encoding
        if (u.getCharset() != null) {
            props.setProperty("encoding", u.getCharset().toString());
        }
    } else {
        String newUrl = url.replace("file:", "");
        File file = new File(newUrl);
        is = new FileInputStream(file);
    }
    File f = getCachedFile();
    if (is == null || isFault()) {
        LOGGER.debug("Url " + url + ": did not receive a response; writing empty file");
        f.createNewFile();
        return;
    }
    FileOutputStream fos = new FileOutputStream(f);
    long sizeCopy = IOUtils.copy(is, fos);
    fos.flush();
    try {
        fos.getFD().sync(); // wait until file has been completely written
    } catch (Exception e) {
        // empty -> just do not crash the thread
    }
    fos.close();
    is.close();

    if (sizeHttp > 0 && sizeHttp != sizeCopy) {
        LOGGER.warn("File not fully cached! " + f.getAbsolutePath());
    }
    LOGGER.debug("Url " + url + " Cached To: " + f.getAbsolutePath());
    PropertiesUtils.store(props, getPropertyFile(), "Cached Url Properties");
}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.FileUtility.java

private void recursiveFileCopy(String destinationDirectory, File source) throws IOException {
    LOGGER.debug("DestinationDirectory - " + destinationDirectory);
    LOGGER.debug("File Listing for " + source.getAbsolutePath() + " - ");
    printArray(source.list());//from   ww w  .ja v a  2  s .c o m
    for (File subFile : source.listFiles()) {
        if (subFile.isDirectory()) {
            File destinationDir = new File(
                    ((destinationDirectory.endsWith("/")) ? destinationDirectory : destinationDirectory + "/")
                            + subFile.getName());
            if (!destinationDir.isDirectory() && !destinationDir.mkdir()) {
                throw new IOException(String.format("Unable to create directory '%s'", destinationDir));
            }
            recursiveFileCopy(destinationDir.getAbsolutePath(), subFile);
        } else {
            FileInputStream fileIn = null;
            FileOutputStream fileOut = null;
            try {
                fileIn = new FileInputStream(subFile);
                fileOut = new FileOutputStream(new File(destinationDirectory + "/" + subFile.getName()));
                copyFiles(fileIn, fileOut);

                fileOut.flush();
                fileOut.getFD().sync();
            } finally {
                if (fileIn != null) {
                    try {
                        fileIn.close();
                    } catch (Exception e) {
                        // Nothing to do
                    }
                }
                if (fileOut != null) {
                    try {
                        fileOut.close();
                    } catch (Exception e) {
                        // Nothing to do
                    }
                }
            }
        }
    }
}

From source file:org.tinymediamanager.core.MediaEntityImageFetcherTask.java

@Override
public void run() {
    long timestamp = System.currentTimeMillis(); // multi episode same file
    try {// w  ww.  jav  a 2  s .  c  o  m
        if (StringUtils.isBlank(filename)) {
            return;
        }

        // don't write jpeg -> write jpg
        if (FilenameUtils.getExtension(filename).equalsIgnoreCase("JPEG")) {
            filename = FilenameUtils.getBaseName(filename) + ".jpg";
        }

        String oldFilename = null;
        try {
            // store old filename at the first image
            if (firstImage) {
                switch (type) {
                case POSTER:
                case BACKGROUND:
                case BANNER:
                case THUMB:
                case CLEARART:
                case DISC:
                case LOGO:
                case CLEARLOGO:
                    oldFilename = entity.getArtworkFilename(MediaFileType.getMediaFileType(type));
                    entity.removeAllMediaFiles(MediaFileType.getMediaFileType(type));
                    break;

                default:
                    return;
                }
            }

            // debug message
            LOGGER.debug("writing " + type + " " + filename);
            Path destFile = entity.getPathNIO().resolve(filename);
            Path tempFile = entity.getPathNIO().resolve(filename + "." + timestamp + ".part"); // multi episode same file

            // check if old and new file are the same (possible if you select it in the imagechooser)
            boolean sameFile = false;
            if (url.startsWith("file:")) {
                String newUrl = url.replace("file:/", "");
                Path file = Paths.get(newUrl);
                if (file.equals(destFile)) {
                    sameFile = true;
                }
            }

            // fetch and store images
            if (!sameFile) {
                Url url1 = new Url(url);
                FileOutputStream outputStream = new FileOutputStream(tempFile.toFile());
                InputStream is = url1.getInputStream();
                IOUtils.copy(is, outputStream);
                outputStream.flush();
                try {
                    outputStream.getFD().sync(); // wait until file has been completely written
                    // give it a few milliseconds
                    Thread.sleep(150);
                } catch (Exception e) {
                    // empty here -> just not let the thread crash
                }
                outputStream.close();
                is.close();

                // check if the file has been downloaded
                if (!Files.exists(tempFile) || Files.size(tempFile) == 0) {
                    throw new Exception("0byte file downloaded: " + filename);
                }

                // delete the old one if exisiting
                if (StringUtils.isNotBlank(oldFilename)) {
                    Path oldFile = entity.getPathNIO().resolve(oldFilename);
                    Utils.deleteFileSafely(oldFile);
                }

                // delete new destination if existing
                Utils.deleteFileSafely(destFile);

                // move the temp file to the expected filename
                if (!Utils.moveFileSafe(tempFile, destFile)) {
                    throw new Exception("renaming temp file failed: " + filename);
                }
            }

            // has tmm been shut down?
            if (Thread.interrupted()) {
                return;
            }

            // set the new image if its the first image
            if (firstImage) {
                LOGGER.debug("set " + type + " " + FilenameUtils.getName(filename));
                ImageCache.invalidateCachedImage(entity.getPathNIO().resolve(filename));
                switch (type) {
                case POSTER:
                case BACKGROUND:
                case BANNER:
                case THUMB:
                case CLEARART:
                case DISC:
                case LOGO:
                case CLEARLOGO:
                    entity.setArtwork(destFile, MediaFileType.getMediaFileType(type));
                    entity.callbackForWrittenArtwork(type);
                    entity.saveToDb();
                    break;

                default:
                    return;
                }
            }
        }

        catch (Exception e) {
            if (e instanceof InterruptedException) {
                // only warning
                LOGGER.warn("interrupted image download");
            } else {
                LOGGER.error("fetch image", e);
            }

            // remove temp file
            Path tempFile = entity.getPathNIO().resolve(filename + "." + timestamp + ".part"); // multi episode same file
            if (Files.exists(tempFile)) {
                Utils.deleteFileSafely(tempFile);
            }

            // fallback
            if (firstImage && StringUtils.isNotBlank(oldFilename)) {
                switch (type) {
                case POSTER:
                case BACKGROUND:
                case BANNER:
                case THUMB:
                case CLEARART:
                case DISC:
                case LOGO:
                case CLEARLOGO:
                    entity.setArtwork(Paths.get(oldFilename), MediaFileType.getMediaFileType(type));
                    entity.callbackForWrittenArtwork(type);
                    entity.saveToDb();
                    break;

                default:
                    return;
                }
            }

            MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, "ArtworkDownload",
                    "message.artwork.threadcrashed", new String[] { ":", e.getLocalizedMessage() }));
        }

    } catch (Exception e) {
        LOGGER.error("crashed thread: ", e);
    }
}

From source file:com.mtgi.analytics.XmlBehaviorEventPersisterTest.java

/** 
 * if the persister was not shut down cleanly, we might have an old log file without a timestamp laying around.
 * make sure log rotation doesn't clobber it.
 *//*from  ww  w.ja v a2  s .  com*/
@Test
public void testOfflineConfigurationChange() throws Exception {

    //generate an old log file with some data, *not* the one currently referenced by our persister.
    File staleFile = new File(persister.getFile() + ".gz");
    staleFile.deleteOnExit();
    assertFalse("sanity check: " + staleFile.getAbsolutePath() + " does not exist", staleFile.exists());

    byte[] data = { 0xC, 0xA, 0xF, 0xE, 0xB, 0xA, 0xB, 0xE };
    FileOutputStream fos = new FileOutputStream(staleFile);
    try {
        fos.write(data);
        fos.flush();
        fos.getFD().sync();
    } finally {
        IOUtils.closeQuietly(fos);
    }
    assertEquals("sanity check: stale log file has content", 8, staleFile.length());
    assertFalse("sanity check: persister currently points to different location",
            staleFile.equals(new File(persister.getFile())));

    //change logging config, such that the next log rotation would cause us to clobber the
    //pre-existing file 'staleFile'.  staleFile should be preserved in a new location with a timestamp
    //suffix.
    persister.setCompress(true);
    persister.rotateLog();
    File newPath = new File(persister.getFile());
    assertEquals("persister now points to stale log file location after rotate", staleFile, newPath);

    //we should be able to locate a backup file in the parent dir somewhere.
    final String backupPrefix = staleFile.getName();
    class BackupLocator implements FilenameFilter {
        File backup = null;
        int matchCount = 0;

        public boolean accept(File dir, String name) {
            if (name.length() > backupPrefix.length() && name.startsWith(backupPrefix)) {
                ++matchCount;
                backup = new File(dir, name);
            }
            return false;
        }
    }
    ;
    BackupLocator locator = new BackupLocator();
    File dir = staleFile.getParentFile();
    dir.listFiles(locator);

    assertEquals("exactly one backup log file found", 1, locator.matchCount);
    //verify backup contents
    FileInputStream fis = new FileInputStream(locator.backup);
    try {
        for (int i = 0; i < data.length; ++i)
            assertEquals("@" + i + " matches", data[i], (byte) fis.read());
        assertEquals("no data remains", -1, fis.read());
    } finally {
        IOUtils.closeQuietly(fis);
        locator.backup.delete();
    }
}