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:phex.util.FileUtils.java

/**
 * Copys the source file to the destination file. Old contents of the
 * destination file will be overwritten.
 * This is a optimized version of the org.apache.commons.io.FileUtils.copy
 * source, with larger file buffer for a faster copy process.
 *
 * @throws IOException in case an IO operation fails
 *//*ww  w  . ja  v  a 2 s  . c  o  m*/
public static void copyFile(File source, File destination, long copyLength) throws IOException {
    // check source exists
    if (!source.exists()) {
        String message = "File " + source + " does not exist";
        throw new FileNotFoundException(message);
    }

    //does destinations directory exist ?
    if (destination.getParentFile() != null && !destination.getParentFile().exists()) {
        forceMkdir(destination.getParentFile());
    }

    //make sure we can write to destination
    if (destination.exists() && !destination.canWrite()) {
        String message = "Unable to open file " + destination + " for writing.";
        throw new IOException(message);
    }

    //makes sure it is not the same file
    if (source.getCanonicalPath().equals(destination.getCanonicalPath())) {
        String message = "Unable to write file " + source + " on itself.";
        throw new IOException(message);
    }

    if (copyLength == 0) {
        truncateFile(destination, 0);
    }

    FileInputStream input = null;
    FileOutputStream output = null;
    try {
        input = new FileInputStream(source);
        output = new FileOutputStream(destination);
        long lengthLeft = copyLength;
        byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, lengthLeft + 1)];
        int read;
        while (lengthLeft > 0) {
            read = input.read(buffer);
            if (read == -1) {
                break;
            }
            lengthLeft -= read;
            output.write(buffer, 0, read);
        }
        output.flush();
        output.getFD().sync();
    } finally {
        IOUtil.closeQuietly(input);
        IOUtil.closeQuietly(output);
    }

    //file copy should preserve file date
    destination.setLastModified(source.lastModified());
}

From source file:edu.usf.cutr.opentripplanner.android.util.JacksonConfig.java

/**
 * Write the given object to Android internal storage for this app
 *
 * @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/*from w  w  w  .  ja  va  2  s  .c  o  m*/
 */
private synchronized static boolean writeToCache(Serializable object) {

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

    if (context != null) {
        try {
            if (object instanceof ObjectMapper) {
                fileName = OBJECT_MAPPER + CACHE_FILE_EXTENSION;
            }
            if (object instanceof ObjectReader) {
                fileName = OBJECT_READER + CACHE_FILE_EXTENSION;
            }

            cacheWriteStartTime = System.nanoTime();
            fileStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            objectStream = new ObjectOutputStream(fileStream);
            objectStream.writeObject(object);
            objectStream.flush();
            fileStream.getFD().sync();
            cacheWriteEndTime = System.nanoTime();
            success = true;

            // Get size of serialized object
            long fileSize = context.getFileStreamPath(fileName).length();

            Log.d("TAG", "Wrote " + fileName + " to cache (" + fileSize + " bytes) in "
                    + df.format(getLastCacheWriteTime()) + " ms.");
        } catch (IOException e) {
            // Reset timestamps to show there was an error
            cacheWriteStartTime = 0;
            cacheWriteEndTime = 0;
            Log.e(TAG, "Couldn't write Jackson object '" + fileName + "' to cache: " + e);
        } finally {
            try {
                if (objectStream != null) {
                    objectStream.close();
                }
                if (fileStream != null) {
                    fileStream.close();
                }
            } catch (Exception e) {
                Log.e(TAG, "Error closing file connections: " + e);
            }
        }
    } else {
        Log.w(TAG,
                "Can't write to cache - no context provided.  If you want to use the cache, call JacksonConfig.setUsingCache(true, context) with a reference to your context.");
    }

    return success;
}

From source file:org.apache.hadoop.io.nativeio.TestNativeIO.java

@Test
public void testGetOwner() throws Exception {
    FileOutputStream fos = new FileOutputStream(new File(TEST_DIR, "testfstat"));
    String owner = NativeIO.getOwner(fos.getFD());
    fos.close();//from   www.  j a  va  2 s .c  om
    LOG.info("Owner: " + owner);

    assertEquals(System.getProperty("user.name"), owner);
}

From source file:org.apache.hadoop.io.nativeio.TestNativeIO.java

@Test
public void testFstat() throws Exception {
    FileOutputStream fos = new FileOutputStream(new File(TEST_DIR, "testfstat"));
    NativeIO.Stat stat = NativeIO.fstat(fos.getFD());
    fos.close();//from ww  w.  ja v a  2  s  .  c  o m
    LOG.info("Stat: " + String.valueOf(stat));

    assertEquals(System.getProperty("user.name"), stat.getOwner());
    assertEquals(NativeIO.Stat.S_IFREG, stat.getMode() & NativeIO.Stat.S_IFMT);
}

From source file:org.apache.druid.segment.loading.LocalDataSegmentFinderTest.java

@Test
public void testPreferNewestSegment() throws Exception {
    dataSourceDir = temporaryFolder.newFolder();
    descriptor1 = new File(dataSourceDir.getAbsolutePath() + "/interval10/v10/0/older", DESCRIPTOR_JSON);
    descriptor2 = new File(dataSourceDir.getAbsolutePath() + "/interval10/v10/0/newer", DESCRIPTOR_JSON);

    descriptor1.getParentFile().mkdirs();
    descriptor2.getParentFile().mkdirs();

    mapper.writeValue(descriptor1, SEGMENT_1);
    mapper.writeValue(descriptor2, SEGMENT_1);

    indexZip1 = new File(descriptor1.getParentFile(), INDEX_ZIP);
    indexZip2 = new File(descriptor2.getParentFile(), INDEX_ZIP);

    FileOutputStream fos1 = new FileOutputStream(indexZip1);
    fos1.getFD().sync();
    fos1.close();//from   w ww  .j  ava  2  s.c  o  m

    Thread.sleep(1000);

    FileOutputStream fos2 = new FileOutputStream(indexZip2);
    fos2.getFD().sync();
    fos2.close();

    final Set<DataSegment> segments = new LocalDataSegmentFinder(mapper)
            .findSegments(dataSourceDir.getAbsolutePath(), false);

    Assert.assertEquals(1, segments.size());
    Assert.assertEquals(indexZip2.getAbsolutePath(), segments.iterator().next().getLoadSpec().get("path"));
}

From source file:org.apache.hadoop.io.nativeio.TestNativeIO.java

@Test
public void testFstatClosedFd() throws Exception {
    FileOutputStream fos = new FileOutputStream(new File(TEST_DIR, "testfstat2"));
    fos.close();//from  w ww .  j av a  2s.  co  m
    try {
        NativeIO.Stat stat = NativeIO.fstat(fos.getFD());
    } catch (IOException e) {
        LOG.info("Got expected exception", e);
    }
}

From source file:com.commonsware.android.andshooter.ScreenshotService.java

void processImage(final byte[] png) {
    new Thread() {
        @Override/*from  w ww.  java2  s . co  m*/
        public void run() {
            File output = new File(getExternalFilesDir(null), "screenshot.png");

            try {
                FileOutputStream fos = new FileOutputStream(output);

                fos.write(png);
                fos.flush();
                fos.getFD().sync();
                fos.close();

                MediaScannerConnection.scanFile(ScreenshotService.this,
                        new String[] { output.getAbsolutePath() }, new String[] { "image/png" }, null);
            } catch (Exception e) {
                Log.e(getClass().getSimpleName(), "Exception writing out screenshot", e);
            }
        }
    }.start();

    beeper.startTone(ToneGenerator.TONE_PROP_ACK);
    stopCapture();
}

From source file:com.commonsware.android.antidoze.ScheduledService.java

private void append(File f, RandomEvent event) {
    try {/*from w  w  w.  j a  v a 2 s  .  c o m*/
        FileOutputStream fos = new FileOutputStream(f, true);
        Writer osw = new OutputStreamWriter(fos);

        osw.write(event.when.toString());
        osw.write(" : ");
        osw.write(Integer.toHexString(event.value));
        osw.write('\n');
        osw.flush();
        fos.flush();
        fos.getFD().sync();
        fos.close();

        Log.d(getClass().getSimpleName(), "logged to " + f.getAbsolutePath());
    } catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Exception writing to file", e);
    }
}

From source file:com.commonsware.android.backup.BackupService.java

private File buildBackup() throws IOException {
    File zipFile = new File(getCacheDir(), BACKUP_FILENAME);

    if (zipFile.exists()) {
        zipFile.delete();//w  w  w. j  a va2s. co  m
    }

    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    zipDir(ZIP_PREFIX_FILES, getFilesDir(), zos);
    zipDir(ZIP_PREFIX_PREFS, getSharedPrefsDir(this), zos);
    zipDir(ZIP_PREFIX_EXTERNAL, getExternalFilesDir(null), zos);
    zos.flush();
    fos.getFD().sync();
    zos.close();

    return (zipFile);
}

From source file:org.mule.util.JarUtils.java

public static void createJarFileEntries(File jarFile, LinkedHashMap entries) throws Exception {
    JarOutputStream jarStream = null;
    FileOutputStream fileStream = null;

    if (jarFile != null) {
        logger.debug("Creating jar file " + jarFile.getAbsolutePath());

        try {//ww  w  . j a  va  2  s  .  c o  m
            fileStream = new FileOutputStream(jarFile);
            jarStream = new JarOutputStream(fileStream);

            if (entries != null && !entries.isEmpty()) {
                Iterator iter = entries.keySet().iterator();
                while (iter.hasNext()) {
                    String jarFilePath = (String) iter.next();
                    Object content = entries.get(jarFilePath);

                    JarEntry entry = new JarEntry(jarFilePath);
                    jarStream.putNextEntry(entry);

                    logger.debug("Adding jar entry " + jarFilePath + " to " + jarFile.getAbsolutePath());

                    if (content instanceof String) {
                        writeJarEntry(jarStream, ((String) content).getBytes());
                    } else if (content instanceof byte[]) {
                        writeJarEntry(jarStream, (byte[]) content);
                    } else if (content instanceof File) {
                        writeJarEntry(jarStream, (File) content);
                    }
                }
            }

            jarStream.flush();
            fileStream.getFD().sync();
        } finally {
            if (jarStream != null) {
                try {
                    jarStream.close();
                } catch (Exception jarNotClosed) {
                    logger.debug(jarNotClosed);
                }
            }
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (Exception fileNotClosed) {
                    logger.debug(fileNotClosed);
                }
            }
        }
    }
}