Example usage for java.io File canWrite

List of usage examples for java.io File canWrite

Introduction

In this page you can find the example usage for java.io File canWrite.

Prototype

public boolean canWrite() 

Source Link

Document

Tests whether the application can modify the file denoted by this abstract pathname.

Usage

From source file:org.eclipse.virgo.ide.jdt.internal.core.util.ClasspathUtils.java

/**
 * Adjusts the last modified timestamp on the source root and META-INF directory to reflect the
 * same date as the MANIFEST.MF.//from  w  w  w  .j a  va 2 s .c  om
 * <p>
 * Note: this is a requirement for the dependency resolution.
 */
public static void adjustLastModifiedDate(IJavaProject javaProject, boolean testBundle) {
    File manifest = BundleManifestUtils.locateManifestFile(javaProject, testBundle);
    if (manifest != null && manifest.canRead()) {
        long lastmodified = manifest.lastModified();
        File metaInfFolder = manifest.getParentFile();
        if (metaInfFolder != null
                && metaInfFolder.getName().equals(BundleManifestCorePlugin.MANIFEST_FOLDER_NAME)
                && metaInfFolder.canWrite()) {
            metaInfFolder.setLastModified(lastmodified);
            File srcFolder = metaInfFolder.getParentFile();
            if (srcFolder != null && srcFolder.canWrite()) {
                srcFolder.setLastModified(lastmodified);
            }
        }
    }
}

From source file:net.sf.sripathi.ws.mock.util.Folder.java

/**
 * Gets the folder information for the path provided.
 * If the folder is not present creates a new folder.
 * /*from ww w.  j a v a  2s  .  co  m*/
 * @param path folder path string.
 * 
 * @return instance of Folder class.
 */
public static Folder getInstance(String path) {

    Folder folder = null;
    Folder.folderMap = new HashMap<String, Folder>();
    Folder.fileSet = new TreeSet<String>();

    try {
        File file = new File(path);

        if (!file.exists()) {
            file.mkdir();
        }

        if (!file.isDirectory() && !file.canRead() && !file.canWrite()) {
            throw new MockException("Unable to read dir " + path + " make sure access is set correctly");
        }

        //Get root and sub directories
        folder = new Folder(path, file);

        Folder.folderMap.put(path, folder);

    } catch (Exception e) {
        throw new MockException("Unable to read dir " + path + " make sure access is set correctly");
    }

    return folder;
}

From source file:com.zimbra.common.util.CliUtil.java

/**
 * Turns on command line editing with JLine.  
 * @param histFilePath path to the history file, or {@code null} to not save history
 * @throws IOException if the history file is not writable or cannot be created
 *///from ww  w.jav a 2  s. co  m
public static void enableCommandLineEditing(String histFilePath) throws IOException {
    File histFile = null;
    if (histFilePath != null) {
        histFile = new File(histFilePath);
        if (!histFile.exists()) {
            if (!histFile.createNewFile()) {
                throw new IOException("Unable to create history file " + histFilePath);
            }
        }
        if (!histFile.canWrite()) {
            throw new IOException(histFilePath + " is not writable");
        }
    }
    ConsoleReader reader = new ConsoleReader();
    if (histFile != null) {
        reader.setHistory(new History(histFile));
    }
    ConsoleReaderInputStream.setIn(reader);
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static String getFileIfCanWrite(String path, String file) {
    File fileObj = new File(path, file);
    if (fileObj.canWrite()) {
        return fileObj.getAbsoluteFile().getAbsolutePath();
    }//from ww  w  .  ja  v a  2  s .co  m
    return null;
}

From source file:com.docd.purefm.test.JavaFileTest.java

private static void testAgainstJavaIoFile(final JavaFile genericFile, final File javaFile) throws Throwable {
    assertEquals(javaFile, genericFile.toFile());
    assertEquals(javaFile.getName(), genericFile.getName());
    assertEquals(javaFile.getAbsolutePath(), genericFile.getAbsolutePath());
    assertEquals(javaFile.canRead(), genericFile.canRead());
    assertEquals(javaFile.canWrite(), genericFile.canWrite());
    assertEquals(javaFile.canExecute(), genericFile.canExecute());
    assertEquals(javaFile.exists(), genericFile.exists());
    assertEquals(javaFile.getPath(), genericFile.getPath());
    assertEquals(javaFile.getParent(), genericFile.getParent());
    assertEquals(javaFile.length(), genericFile.length());
    final File parentFile;
    final GenericFile genericParentFile = genericFile.getParentFile();
    if (genericParentFile == null) {
        parentFile = null;//from   ww w . j  a v a  2s  .  c o m
    } else {
        parentFile = genericParentFile.toFile();
    }
    assertEquals(javaFile.getParentFile(), parentFile);
    assertEquals(javaFile.length(), genericFile.length());
    try {
        assertEquals(FileUtils.isSymlink(javaFile), genericFile.isSymlink());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        assertEquals(javaFile.getCanonicalPath(), genericFile.getCanonicalPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
    assertEquals(javaFile.length(), genericFile.length());
    assertEquals(javaFile.lastModified(), genericFile.lastModified());
    assertEquals(javaFile.isDirectory(), genericFile.isDirectory());
    assertTrue(Arrays.equals(javaFile.list(), genericFile.list()));
    assertTrue(Arrays.equals(javaFile.listFiles(), genericFile.listFiles()));
}

From source file:aiai.apps.commons.utils.ZipUtils.java

/**
 * Unzips a zip file into the given destination directory.
 *
 * The archive file MUST have a unique "root" folder. This root folder is
 * skipped when unarchiving.// ww  w  . j  a v a2s.co  m
 *
 */
public static void unzipFolder(File archiveFile, File zipDestinationFolder) {

    log.debug("Start unzipping archive file");
    log.debug("'\tzip archive file: {}", archiveFile.getAbsolutePath());
    log.debug("'\t\tis exist: {}", archiveFile.exists());
    log.debug("'\t\tis writable: {}", archiveFile.canWrite());
    log.debug("'\t\tis readable: {}", archiveFile.canRead());
    log.debug("'\ttarget dir: {}", zipDestinationFolder.getAbsolutePath());
    log.debug("'\t\tis exist: {}", zipDestinationFolder.exists());
    log.debug("'\t\tis writable: {}", zipDestinationFolder.canWrite());
    try (MyZipFile zipFile = new MyZipFile(archiveFile)) {

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zipEntry = entries.nextElement();
            log.debug("'\t\tzip entry: {}, is directory: {}", zipEntry.getName(), zipEntry.isDirectory());

            String name = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                if (name.endsWith("/") || name.endsWith("\\")) {
                    name = name.substring(0, name.length() - 1);
                }

                File newDir = new File(zipDestinationFolder, name);
                log.debug("'\t\t\tcreate dirs in {}", newDir.getAbsolutePath());
                if (!newDir.mkdirs()) {
                    throw new RuntimeException("Creation of target dir was failed, target dir: "
                            + zipDestinationFolder + ", entity: " + name);
                }
            } else {
                File destinationFile = DirUtils.createTargetFile(zipDestinationFolder, name);
                if (destinationFile == null) {
                    throw new RuntimeException("Creation of target file was failed, target dir: "
                            + zipDestinationFolder + ", entity: " + name);
                }
                if (!destinationFile.getParentFile().exists()) {
                    destinationFile.getParentFile().mkdirs();
                }
                log.debug("'\t\t\tcopy content of zip entry to file {}", destinationFile.getAbsolutePath());
                FileUtils.copyInputStreamToFile(zipFile.getInputStream(zipEntry), destinationFile);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Unzip failed:", e);
    }
}

From source file:com.microsoft.tfs.core.persistence.VersionedVendorFilesystemPersistenceStore.java

/**
 * Gets the local directory to store things in for the given vendor,
 * application, and version./*from  w w  w . j a va  2s .  c  om*/
 *
 * @param vendorName
 *        the vendor name (must not be <code>null</code> or empty)
 * @param applicationName
 *        the application name (must not be <code>null</code> or empty)
 * @param version
 *        the version string (must not be <code>null</code> or empty)
 * @return the {@link File} for the constructed path, like
 *         "~/.vendorName/applicationName/version"
 */
private static File makeDirectoryForVendorApplicationVersion(final String vendorName,
        final String applicationName, final String version) {
    Check.notNullOrEmpty(vendorName, "vendorName"); //$NON-NLS-1$
    Check.notNullOrEmpty(applicationName, "applicationName"); //$NON-NLS-1$
    Check.notNullOrEmpty(version, "version"); //$NON-NLS-1$

    String path = PlatformMiscUtils.getInstance()
            .getEnvironmentVariable(EnvironmentVariables.TEE_PROFILE_DIRECTORY);

    if (path != null) {
        path = path.trim();
        try {
            if (StringUtil.isNullOrEmpty(path)) {
                log.warn(
                        "User specified profile location path is empty, TEE will use default profile location."); //$NON-NLS-1$
            } else if (!LocalPath.isPathRooted(path)) {
                log.warn("User specified location " //$NON-NLS-1$
                        + path + "is not an absolute path. TEE will use default profile location."); //$NON-NLS-1$
            } else {
                final File file = new File(path).getCanonicalFile();
                if (!file.exists()) {
                    file.mkdirs();
                }

                if (file.exists() && file.isDirectory() && file.canRead() && file.canWrite()) {
                    return file;
                } else {
                    log.warn("User specified location " //$NON-NLS-1$
                            + path + "can not be accessed. TEE will use default profile location."); //$NON-NLS-1$
                }
            }
        } catch (final IOException e) {
            log.error("Exception testing profile location specified by the user: " //$NON-NLS-1$
                    + path + ".\n" //$NON-NLS-1$
                    + "TEE will use the default profile location.", e); //$NON-NLS-1$
        }
    }

    if (Platform.isCurrentPlatform(Platform.WINDOWS)) {
        /*
         * Check to see if we can find the user's local application data
         * directory.
         */
        path = SpecialFolders.getLocalApplicationDataPath();
        if (path == null || path.length() == 0) {
            /*
             * If the user has never logged onto this box they will not have
             * a local application data directory. Check to see if they have
             * a roaming network directory that moves with them.
             */
            path = SpecialFolders.getApplicationDataPath();
            if (path == null || path.length() == 0) {
                /*
                 * The user does not have a roaming network directory
                 * either. Just place the cache in the common area.
                 */
                path = SpecialFolders.getCommonApplicationDataPath();
            }
        }

        // "C:\\Users\\[username]\\AppData\\Local\\Microsoft
        path = path + File.separator + vendorName;
    } else if (Platform.isCurrentPlatform(Platform.MAC_OS_X)) {
        // Use the user's Library directory, creating a vendor name
        // directory there.

        // "~/Library/Application Support/Microsoft"
        path = System.getProperty("user.home") //$NON-NLS-1$
                + File.separator + "Library" //$NON-NLS-1$
                + File.separator + "Application Support" //$NON-NLS-1$
                + File.separator + vendorName;
    } else {
        // Consider all other operating systems a normal variant of
        // Unix. We lowercase the path components because that's closer to
        // convention.

        // "~/.microsoft"
        path = System.getProperty("user.home") + File.separator + "." + vendorName.toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$
    }

    path = path + File.separator + applicationName + File.separator + version;

    log.debug(MessageFormat.format("Using path {0} for vendorName {1}, application {2}, and version {3}", //$NON-NLS-1$
            path, vendorName, applicationName, version));

    return new File(path);
}

From source file:FileUtil.java

public static void copyFile(String from, String to, Boolean overwrite) {

    try {/*  w  ww .  ja va  2  s  .com*/
        File fromFile = new File(from);
        File toFile = new File(to);

        if (!fromFile.exists()) {
            throw new IOException("File not found: " + from);
        }
        if (!fromFile.isFile()) {
            throw new IOException("Can't copy directories: " + from);
        }
        if (!fromFile.canRead()) {
            throw new IOException("Can't read file: " + from);
        }

        if (toFile.isDirectory()) {
            toFile = new File(toFile, fromFile.getName());
        }

        if (toFile.exists() && !overwrite) {
            throw new IOException("File already exists.");
        } else {
            String parent = toFile.getParent();
            if (parent == null) {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists()) {
                throw new IOException("Destination directory does not exist: " + parent);
            }
            if (dir.isFile()) {
                throw new IOException("Destination is not a valid directory: " + parent);
            }
            if (!dir.canWrite()) {
                throw new IOException("Can't write on destination: " + parent);
            }
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {

            fis = new FileInputStream(fromFile);
            fos = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

        } finally {
            if (from != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
            }
            if (to != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
            }
        }

    } catch (Exception e) {
        System.out.println("Problems when copying file.");
    }
}

From source file:gridool.db.sql.ParallelSQLMapTask.java

private static int executeCopyIntoFile(@Nonnull final Connection conn, @Nonnull final String mapQuery,
        @Nonnull final String taskTableName, @Nonnull final File outFile) throws SQLException {
    if (!outFile.canWrite()) {// sanity check
        throw new IllegalStateException("File is not writable: " + outFile.getAbsolutePath());
    }//  ww w  .jav  a  2 s .c  o m
    assert (mapQuery.indexOf(';') == -1) : mapQuery;
    String filepath = outFile.getAbsolutePath();
    final String copyIntoQuery;
    if (DO_WORKAROUND_FOR_COPYINTOFILE) {
        String tmpTableName = "copy_" + taskTableName;
        String createTmpTableQuery = "CREATE LOCAL TEMPORARY TABLE \"" + tmpTableName + "\" AS (" + mapQuery
                + ") WITH DATA";
        int ret = JDBCUtils.update(conn, createTmpTableQuery);
        if (LOG.isInfoEnabled()) {
            LOG.info("Create a LOCAL TEMPORARY TABLE: " + ret + '\n' + createTmpTableQuery);
        }
        copyIntoQuery = "COPY (SELECT * FROM \"" + tmpTableName + "\") INTO '" + filepath
                + "' USING DELIMITERS '|','\n','\"'";
    } else {
        copyIntoQuery = "COPY (" + mapQuery + ") INTO '" + filepath + "' USING DELIMITERS '|','\n','\"'";
    }
    int affectedRows = JDBCUtils.update(conn, copyIntoQuery);
    if (affectedRows < 0) {
        LOG.warn("Failed to execute a Map SQL query? [Affected rows=" + affectedRows + "]: \n" + copyIntoQuery);
    } else {
        if (LOG.isInfoEnabled()) {
            LOG.info("Executing a Map SQL query [Affected rows=" + affectedRows + "]: \n" + copyIntoQuery);
        }
    }
    return affectedRows;
}

From source file:com.dnielfe.manager.utils.SimpleUtils.java

public static void deleteTarget(Activity activity, String path, String dir) {
    File target = new File(path);

    if (!target.exists()) {
        return;//w w  w  . j  a va 2s. c  o  m
    } else if (target.isFile() && target.canWrite()) {
        target.delete();
        requestMediaScanner(activity, target);
        return;
    } else if (target.isDirectory() && target.canRead()) {
        String[] file_list = target.list();

        if (file_list != null && file_list.length == 0) {
            target.delete();
            return;
        } else if (file_list != null && file_list.length > 0) {

            for (int i = 0; i < file_list.length; i++) {
                File temp_f = new File(target.getAbsolutePath() + "/" + file_list[i]);

                if (temp_f.isDirectory())
                    deleteTarget(activity, temp_f.getAbsolutePath(), dir);
                else if (temp_f.isFile()) {
                    temp_f.delete();
                    requestMediaScanner(activity, temp_f);
                }
            }
        }

        if (target.exists())
            if (target.delete())
                return;
    } else if (target.exists() && !target.delete()) {
        RootCommands.DeleteFileRoot(path, dir);
    }
    return;
}