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:org.eclipse.kura.core.deployment.install.InstallImpl.java

private void addPackageToConfFile(String packageName, String packageUrl) {
    Properties deployedPackages = getDeployedPackages();
    deployedPackages.setProperty(packageName, packageUrl);

    if (this.dpaConfPath == null) {
        s_logger.warn(MESSAGE_CONFIGURATION_FILE_NOT_SPECIFIED);
        return;// www  .  ja va  2s .  c  o  m
    }

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(this.dpaConfPath);
        deployedPackages.store(fos, null);
        fos.flush();
        fos.getFD().sync();
    } catch (IOException e) {
        s_logger.error("Error writing package configuration file", e);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            s_logger.error("Exception while closing opened resources!", e);
        }
    }
}

From source file:org.eclipse.kura.core.deployment.install.InstallImpl.java

public void removePackageFromConfFile(String packageName) {
    Properties deployedPackages = getDeployedPackages();
    deployedPackages.remove(packageName);

    if (this.dpaConfPath == null) {
        s_logger.warn(MESSAGE_CONFIGURATION_FILE_NOT_SPECIFIED);
        return;//from  w w  w. j a v  a2  s  .  c  om
    }

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(this.dpaConfPath);
        deployedPackages.store(fos, null);
        fos.flush();
        fos.getFD().sync();
    } catch (IOException e) {
        s_logger.error("Error writing package configuration file", e);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            s_logger.error("Exception while closing opened resources!", e);
        }
    }
}

From source file:org.eclipse.kura.deployment.agent.impl.DeploymentAgent.java

private void addPackageToConfFile(String packageName, String packageUrl) {
    this.m_deployedPackages.setProperty(packageName, packageUrl);

    if (this.m_dpaConfPath == null) {
        s_logger.warn("Configuration file not specified");
        return;/*from   w ww.ja va2 s  .com*/
    }

    try {
        FileOutputStream fos = new FileOutputStream(this.m_dpaConfPath);
        this.m_deployedPackages.store(fos, null);
        fos.flush();
        fos.getFD().sync();
        fos.close();
    } catch (IOException e) {
        s_logger.error("Error writing package configuration file", e);
    }
}

From source file:org.eclipse.kura.deployment.agent.impl.DeploymentAgent.java

private void removePackageFromConfFile(String packageName) {
    this.m_deployedPackages.remove(packageName);

    if (this.m_dpaConfPath == null) {
        s_logger.warn("Configuration file not specified");
        return;//from w w  w  .  j ava 2 s  .c  om
    }

    try {
        FileOutputStream fos = new FileOutputStream(this.m_dpaConfPath);
        this.m_deployedPackages.store(fos, null);
        fos.flush();
        fos.getFD().sync();
        fos.close();
    } catch (IOException e) {
        s_logger.error("Error writing package configuration file", e);
    }
}

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

/**
 * Copies the file from the specified file path to a backup directory. The backup directory is created under the
 * baseDirectory (i.e. baseDirectory/backup/yyyy-MM-dd_HH-mm-ss/file-path).
 * /*  ww w .ja  v  a2  s.  c o  m*/
 * @param baseDirectory The base directory to create the backup directory in and where the original files are
 *        located.
 * @param sourceFileName The file name to be backed up.
 * @param fromBaseDir The directory path under the base directory where the files are located.
 * @param date The date the objects are backed up. Convenient for organizing all files in the same backup directory
 *        by time.
 * @return The destination file
 * @throws IOException
 */
public String copyBackupFile(final String baseDirectory, final String fromBaseDir, final String sourceFileName,
        Date date) throws IOException {
    String separator = System.getProperty("file.separator");

    StringBuilder src = new StringBuilder(baseDirectory);
    src.append(separator).append(fromBaseDir).append(separator).append(sourceFileName);

    final String sourceFilePath = src.toString();

    StringBuilder dest = new StringBuilder(baseDirectory);
    dest.append(separator).append("backup").append(separator)
            .append(new SimpleDateFormat(BACKUP_SUB_DIR_FORMAT).format(date)).append(separator)
            .append(fromBaseDir);

    String destinationDirName = dest.toString();

    /*
     * Test to see if the backup dir can be created, if not create the backup file in the current directory.
     */
    File destinationDirectory = new File(destinationDirName);
    if (!destinationDirectory.isDirectory() && !destinationDirectory.mkdirs()) {
        LOGGER.warn("Unable to create directory '" + destinationDirName + "' for backup files." + " Using '"
                + baseDirectory + separator + fromBaseDir + "' directory instead.");

        destinationDirName = baseDirectory + separator + fromBaseDir;
    }

    String destinationFile = destinationDirName + separator + sourceFileName;

    LOGGER.debug(
            "Backing up source file [" + sourceFilePath + "] to destination file [" + destinationFile + "], ");

    InputStream in = null;
    FileOutputStream out = null;

    try {
        final File source = new File(sourceFilePath);
        final File destination = new File(destinationFile);
        if (source.exists()) {
            in = new FileInputStream(source);
            out = new FileOutputStream(destination);
            copyFiles(in, out);
            out.flush();
            out.getFD().sync();
        } else {
            // the destination is null as there was no file to copy
            return null;
        }
        LOGGER.debug(
                "DESTINATION FILE- " + destination.getAbsolutePath() + " -Exists: " + destination.isFile());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOGGER.warn("Error closing input stream from file: " + sourceFileName + ".  Cause: "
                        + e.getMessage());
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                LOGGER.warn("Error closing output stream to file: " + destinationFile + ".  Cause: "
                        + e.getMessage());
            }
        }
    }
    return destinationFile;
}

From source file:com.commonsware.android.documents.consumer.DurablizerService.java

private Uri makeLocalCopy(Uri document) {
    DocumentFile docFile = buildDocFileForUri(document);
    Uri result = null;//from   w  w  w.j  a  v a2 s .  c o  m

    if (docFile.getName() != null) {
        File f = new File(getFilesDir(), docFile.getName());

        try {
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            InputStream in = getContentResolver().openInputStream(document);

            try {
                byte[] buffer = new byte[8192];
                int len = 0;

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

                out.flush();
                result = Uri.fromFile(f);
            } finally {
                fos.getFD().sync();
                out.close();
                in.close();
            }
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Exception copying content to file", e);
        }
    }

    return (result);
}

From source file:tufts.vue.action.ActionUtil.java

private static void doMarshallMap(final File targetFile, final File tmpFile, final LWMap map)
        throws java.io.IOException, org.exolab.castor.xml.MarshalException,
        org.exolab.castor.xml.ValidationException, org.exolab.castor.mapping.MappingException {
    final String path = tmpFile.getAbsolutePath().replaceAll("%20", " ");
    final FileOutputStream fos = new FileOutputStream(path);
    final OutputStreamWriter writer;
    FileDescriptor FD = null;//  ww w  . java2 s  .  c om

    try {
        FD = fos.getFD();
        // getting the FileDescriptor is not required -- we just use it
        // for a final call to sync after we save to increase the likelyhood
        // of our save file actually making it to disk.
    } catch (Throwable t) {
        Log.warn("No FileDescriptor for " + path + "; failsafe sync will be skipped: " + t);
    }

    if (OUTPUT_ENCODING.equals("UTF-8") || OUTPUT_ENCODING.equals("UTF8")) {
        writer = new OutputStreamWriter(fos, OUTPUT_ENCODING);
    } else {

        // For the actual file writer we can use the default encoding because we're
        // marshalling specifically in US-ASCII.  E.g., because we direct castor to
        // fully encode any special characters via setEncoding("US-ASCII"), we'll
        // only have ASCII chars to write anyway, and any default encoding will
        // handle that...

        writer = new OutputStreamWriter(fos);

        // below creates duplicate FOS, but may be better for debug?  (MarshallException's can find file?)
        //if (FD == null)
        //    writer = new FileWriter(path);
        //else
        //    writer = new FileWriter(FD);

    }

    if (DEBUG.IO) {
        try {
            Log.debug(String.format("%s; %s; encoding: \"%s\", which will represent \"%s\" XML content",
                    tmpFile, writer, writer.getEncoding(), OUTPUT_ENCODING));
        } catch (Throwable t) {
            Log.warn(t);
        }
    }

    //=======================================================
    // Marshall the map to the tmp file:
    // ---------------------------------

    marshallMapToWriter(writer, map, targetFile, tmpFile);

    //=======================================================

    // Run a filesystem sync if we can just to be sure: Especially helpful on some
    // linux file systems, such as Ext3, which may not normally touch the disk for
    // another 5 seconds, or XFS/Ext4, which may take their own sweet time.
    // For more see:
    // https://bugs.launchpad.net/ubuntu/+source/linux/+bug/317781/comments/54

    if (DEBUG.IO)
        Log.debug("flushing " + writer);
    writer.flush();

    if (FD != null) {
        try {
            if (DEBUG.IO)
                Log.debug("syncing " + FD + "; for " + tmpFile);
            // just as backup -- must however be done before writer.close()
            FD.sync();
            Log.info(" sync'd " + FD + "; for " + tmpFile);
        } catch (Throwable t) {
            Log.warn("after save to " + targetFile + "; sync failed: " + t);
        }
    }

    if (DEBUG.IO)
        Log.debug("closing " + writer);
    writer.close();
    if (DEBUG.IO)
        Log.debug(" closed " + writer);

}

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

private void writeFileFromBase64(final String text, final String destinationFile) throws IOException {
    FileOutputStream out = null;
    try {/* w ww.ja  v a  2s  .  c  o m*/
        out = new FileOutputStream(new File(destinationFile));
        final InputStream in = new ByteArrayInputStream(Base64.decodeBase64(text.getBytes()));
        fileUtility.copyFiles(in, out);

        out.flush();
        out.getFD().sync();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.warn("Error closing output stream to file: " + destinationFile + ".  Cause: "
                        + e.getMessage());
            }
        }
    }
}

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

/**
 * Copy a file from one location on the agent's machine to another location on the agent's machine
 *///www  . j a v a  2  s.  c  om
public void copyFile(ConfigResponse config) throws PluginException {
    String sourcePath = config.getValue("SOURCE");
    String destinationPath = config.getValue("DESTINATION");

    InputStream in = null;
    FileOutputStream out = null;

    try {
        File sourceFile = new File(sourcePath);
        in = new FileInputStream(sourceFile);

        File destFile = new File(destinationPath);
        out = new FileOutputStream(destFile);

        fileUtility.copyFiles(in, out);

        out.flush();
        out.getFD().sync();

        this.filePermissionsChanger.changeFilePermissions(destFile);
        this.fileOwnershipChanger.changeFileOwnership(destFile,
                config.getValue(Utils.SERVER_RESOURCE_CONFIG_PROCESS_USERNAME),
                config.getValue(Utils.SERVER_RESOURCE_CONFIG_PROCESS_GROUP));
    } catch (IOException e) {
        logger.warn("An error occured with a stream: " + e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.warn("An error occurred upon closing the input stream: " + e.getMessage(), e);
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.warn("An error occurred upon closing the output stream: " + e.getMessage());
            }
        }
    }
}

From source file:org.eclipse.kura.net.admin.visitor.linux.HostapdConfigWriter.java

private void copyFile(String data, File destination) throws KuraException {
    FileOutputStream fos = null;
    PrintWriter pw = null;//  www.jav  a  2 s  . c  om
    try {
        fos = new FileOutputStream(destination);
        pw = new PrintWriter(fos);
        pw.write(data);
        pw.flush();
        fos.getFD().sync();

        setPermissions(destination.toString());
    } catch (IOException e) {
        throw KuraException.internalError(e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ex) {
                s_logger.error("I/O Exception while closing BufferedReader!");
            }
        }
        if (pw != null) {
            pw.close();
        }
    }
}