Java Code Examples for java.io.File#canWrite()

The following examples show how to use java.io.File#canWrite() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PropertyContextFactory.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void savePropertyContext(File settingsDir, PropertyContext context)
{
	File file = new File(settingsDir, context.getName());
	if (file.exists() && !file.canWrite())
	{
		Logging.errorPrint("WARNING: Could not update settings file: " + file.getAbsolutePath());
		return;
	}
	try(OutputStream out = new FileOutputStream(file))
	{
		context.beforePropertiesSaved();
		context.properties.store(out, null);
	}
	catch (IOException ex)
	{
		Logging.errorPrint("Error occurred while storing properties", ex);
	}
}
 
Example 2
Source File: FileUtils.java    From erflute with Apache License 2.0 6 votes vote down vote up
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (srcFile == null)
        throw new NullPointerException("Source must not be null");
    if (destFile == null)
        throw new NullPointerException("Destination must not be null");
    if (!srcFile.exists())
        throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
    if (srcFile.isDirectory())
        throw new IOException("Source '" + srcFile + "' exists but is a directory");
    if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath()))
        throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
    if (destFile.getParentFile() != null && !destFile.getParentFile().exists() && !destFile.getParentFile().mkdirs())
        throw new IOException("Destination '" + destFile + "' directory cannot be created");
    if (destFile.exists() && !destFile.canWrite()) {
        throw new IOException("Destination '" + destFile + "' exists but is read-only");
    } else {
        doCopyFile(srcFile, destFile, preserveFileDate);
        return;
    }
}
 
Example 3
Source File: Utils.java    From hipda with GNU General Public License v2.0 6 votes vote down vote up
public static void cleanShareTempFiles() {
    File destFile = HiApplication.getAppContext().getExternalCacheDir();
    if (destFile != null && destFile.exists() && destFile.isDirectory() && destFile.canWrite()) {
        File[] files = destFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.startsWith(Constants.FILE_SHARE_PREFIX);
            }
        });
        if (files != null) {
            for (File f : files) {
                f.delete();
            }
        }
    }
}
 
Example 4
Source File: FileUtils.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
public static boolean moveDocument(File fileFrom, File fileTo, String name) {

        if (fileTo.isDirectory() && fileTo.canWrite()) {
            if (fileFrom.isFile()) {
                return copyDocument(fileFrom, fileTo, name);
            } else if (fileFrom.isDirectory()) {
                File[] filesInDir = fileFrom.listFiles();
                File filesToDir = new File(fileTo, fileFrom.getName());
                if (!filesToDir.mkdirs()) {
                    return false;
                }

                for (int i = 0; i < filesInDir.length; i++) {
                    moveDocument(filesInDir[i], filesToDir, null);
                }
                return true;
            }
        } else {
            return false;
        }
        return false;
    }
 
Example 5
Source File: OpenLyricsWriter.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Write the XML into the file on the filesystem.
 *
 * @param xfile
 */
public void writeToFile(File xfile, boolean overwrite)
        throws OpenLyricsWriterFileExistsException,
               OpenLyricsWriterWriteErrorException,
               TransformerConfigurationException,
               TransformerException {
    if (!overwrite && xfile.exists()) {
        throw new OpenLyricsWriterFileExistsException(String.format("The file %s exists.", xfile.getAbsolutePath()));
    }

    if (overwrite && xfile.exists() && !xfile.canWrite()) {
        throw new OpenLyricsWriterWriteErrorException(String.format("Write access denied file %s exists.", xfile.getAbsolutePath()));
    }

    // Write XML
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    DOMSource source = new DOMSource(this.doc);
    StreamResult result = new StreamResult(xfile);

    //transformer.transform(source, result);
    transformer.transform(source, new StreamResult(System.out));
}
 
Example 6
Source File: Utility.java    From hedera-mirror-node with Apache License 2.0 6 votes vote down vote up
public static void ensureDirectory(Path path) {
    if (path == null) {
        throw new IllegalArgumentException("Empty path");
    }

    File directory = path.toFile();
    directory.mkdirs();

    if (!directory.exists()) {
        throw new IllegalStateException("Unable to create directory " + directory.getAbsolutePath());
    }
    if (!directory.isDirectory()) {
        throw new IllegalStateException("Not a directory " + directory.getAbsolutePath());
    }
    if (!directory.canRead() || !directory.canWrite()) {
        throw new IllegalStateException("Insufficient permissions for directory " + directory.getAbsolutePath());
    }
}
 
Example 7
Source File: ApkBuilder.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Checks an output {@link File} object.
 * This checks the following:
 * - the file is not an existing directory.
 * - if the file exists, that it can be modified.
 * - if it doesn't exists, that a new file can be created.
 * @param file the File to check
 * @throws ApkCreationException If the check fails
 */
private void checkOutputFile(File file) throws ApkCreationException {
    if (file.isDirectory()) {
        throw new ApkCreationException("%s is a directory!", file);
    }

    if (file.exists()) { // will be a file in this case.
        if (!file.canWrite()) {
            throw new ApkCreationException("Cannot write %s", file);
        }
    } else {
        try {
            if (!file.createNewFile()) {
                throw new ApkCreationException("Failed to create %s", file);
            }
        } catch (IOException e) {
            throw new ApkCreationException(
                    "Failed to create '%1$ss': %2$s", file, e.getMessage());
        }
    }
}
 
Example 8
Source File: SVNFileModificationValidator.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private boolean isReadOnly(IFile file) {
	if (file == null) return false;
	File fsFile = file.getLocation().toFile();
	if (fsFile == null || fsFile.canWrite())
		return false;
	else
		return true;
}
 
Example 9
Source File: BasicProjectPanelVisual.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
boolean valid(WizardDescriptor wizardDescriptor) {
    if (projectNameTextField.getText().length() == 0) {
        // Display name not specified
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Name is not a valid folder name.");
        return false;
    }
    File f = FileUtil.normalizeFile(new File(projectLocationTextField.getText()).getAbsoluteFile());
    if (!f.isDirectory()) {
        // folder not a directory
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Folder is not a valid path.");
        return false;
    }
    final File destFolder = FileUtil.normalizeFile(new File(createdFolderTextField.getText()).getAbsoluteFile());
    File projLoc = destFolder;
    while (projLoc != null && !projLoc.exists()) {
        projLoc = projLoc.getParentFile();
    }
    if (projLoc == null || !projLoc.canWrite()) {
        // can't create folder
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Folder cannot be created.");
        return false;
    }
    if (FileUtil.toFileObject(projLoc) == null) {
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Folder is not a valid path.");
        return false;
    }
    File[] kids = destFolder.listFiles();
    if (destFolder.exists() && kids != null && kids.length > 0) {
        // Folder exists and is not empty
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Folder already exists and is not empty.");
        return false;
    }
    wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "");
    return true;
}
 
Example 10
Source File: FatJarPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the ANT script file can be overwritten.
 * If the JAR package setting does not allow to overwrite the JAR
 * then a dialog will ask the user again.
 *
 * @param	parent	the parent for the dialog,
 * 			or <code>null</code> if no dialog should be presented
 * @return	<code>true</code> if it is OK to create the JAR
 */
private boolean canCreateAntScript(Shell parent) {

	File file= fAntScriptLocation.toFile();
	if (file.exists()) {
		if (!file.canWrite())
			return false;

		if (fJarPackage.allowOverwrite())
			return true;

		return parent != null && JarPackagerUtil.askForOverwritePermission(parent, fAntScriptLocation, true);
	}

	// Test if directory exists
	String path= file.getAbsolutePath();
	int separatorIndex= path.lastIndexOf(File.separator);
	if (separatorIndex == -1) // i.e.- default directory, which is fine
		return true;

	File directory= new File(path.substring(0, separatorIndex));
	if (!directory.exists()) {
		if (FatJarPackagerUtil.askToCreateAntScriptDirectory(parent, directory))
			return directory.mkdirs();
		else
			return false;
	}

	return true;
}
 
Example 11
Source File: MainApp.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Public Main App constructor
 */
public MainApp() {
    super();

    initEnvVariable();
    logger = LoggerFactory.getLogger(MainApp.class);

    logger.info("Version Java de l'utilisateur: " + System.getProperty("java.version"));
    logger.info("Architecture du système utilisateur: " + System.getProperty("os.arch"));
    logger.info("Nom du système utilisateur: " + System.getProperty("os.name"));
    logger.info("Version du système utilisateur: " + System.getProperty("os.version"));
    logger.info("Emplacement du fichier de log: " + System.getProperty("zw.logPath"));

    if(args.length > 0) {
        config = new Configuration(args[0]);
    } else {
        File sample = new File(System.getProperty(Constant.JVM_KEY_USER_HOME));
        if(sample.canWrite()) {
            defaultHome = sample;
        } else {
            JFileChooser fr = new JFileChooser();
            FileSystemView fw = fr.getFileSystemView();
            defaultHome = fw.getDefaultDirectory();
        }
        logger.info("Répertoire Home par defaut : "+defaultHome);
        config = new Configuration(defaultHome.getAbsolutePath());
    }
    zdsutils = new ZdsHttp(config);
    mdUtils = new Markdown();
}
 
Example 12
Source File: VDS2PegasusProperties.java    From pegasus with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the destination location for existence, if it can be created, if it is writable etc.
 *
 * @param dir is the new base directory to optionally create.
 * @throws IOException in case of error while writing out files.
 */
protected static void sanityCheck(File dir) throws IOException {
    if (dir.exists()) {
        // location exists
        if (dir.isDirectory()) {
            // ok, isa directory
            if (dir.canWrite()) {
                // can write, all is well
                return;
            } else {
                // all is there, but I cannot write to dir
                throw new IOException("Cannot write to existing directory " + dir.getPath());
            }
        } else {
            // exists but not a directory
            throw new IOException(
                    "Destination "
                            + dir.getPath()
                            + " already "
                            + "exists, but is not a directory.");
        }
    } else {
        // does not exist, try to make it
        if (!dir.mkdirs()) {
            throw new IOException("Unable to create directory destination " + dir.getPath());
        }
    }
}
 
Example 13
Source File: VaultSession.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void validateKeystoreURL() throws Exception {

        File f = new File(keystoreURL);
        if (!f.exists()) {
            throw new Exception(String.format("Keystore '%s' doesn't exist." + "\nkeystore could be created: "
            + "keytool -genseckey -alias Vault -storetype jceks -keyalg AES -keysize 128 -storepass secretsecret -keypass secretsecret -keystore %s",
                    keystoreURL, keystoreURL));
        } else if (!f.canWrite() || !f.isFile()) {
            throw new Exception(String.format("Keystore [%s] is not writable or not a file.", keystoreURL));
        }
    }
 
Example 14
Source File: GraphActivity.java    From ncalc with GNU General Public License v3.0 5 votes vote down vote up
private void saveImage() {
    try {
        File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()) {
            Date d = new Date();
            File imageLoc = new File(root, "com/duy/example/com.duy.calculator/graph/" + d.getMonth() + d.getDay() + d.getHours() + d.getMinutes() + d.getSeconds() + ".png");
            FileOutputStream out = new FileOutputStream(imageLoc);
        } else {
            Toast.makeText(GraphActivity.this, getString(R.string.cannotwrite), Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(GraphActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}
 
Example 15
Source File: ProjectOrModuleNameStep.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean validateNameAndPath(@Nonnull NewModuleWizardContext context) throws WizardStepValidationException {
  final String name = myNamePathComponent.getNameValue();
  if (name.length() == 0) {
    final ApplicationInfo info = ApplicationInfo.getInstance();
    throw new WizardStepValidationException(IdeBundle.message("prompt.new.project.file.name", info.getVersionName(), context.getTargetId()));
  }

  final String projectFileDirectory = myNamePathComponent.getPath();
  if (projectFileDirectory.length() == 0) {
    throw new WizardStepValidationException(IdeBundle.message("prompt.enter.project.file.location", context.getTargetId()));
  }

  final boolean shouldPromptCreation = myNamePathComponent.isPathChangedByUser();
  if (!ProjectWizardUtil.createDirectoryIfNotExists(IdeBundle.message("directory.project.file.directory", context.getTargetId()), projectFileDirectory, shouldPromptCreation)) {
    return false;
  }

  final File file = new File(projectFileDirectory);
  if (file.exists() && !file.canWrite()) {
    throw new WizardStepValidationException(String.format("Directory '%s' is not writable!\nPlease choose another project location.", projectFileDirectory));
  }

  boolean shouldContinue = true;
  final File projectDir = new File(myNamePathComponent.getPath(), Project.DIRECTORY_STORE_FOLDER);
  if (projectDir.exists()) {
    int answer = Messages
            .showYesNoDialog(IdeBundle.message("prompt.overwrite.project.folder", projectDir.getAbsolutePath(), context.getTargetId()), IdeBundle.message("title.file.already.exists"), Messages.getQuestionIcon());
    shouldContinue = (answer == Messages.YES);
  }

  return shouldContinue;
}
 
Example 16
Source File: FileBasedObjectStore.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected File checkPersistenceDirPlausible(File dir) {
    checkNotNull(dir, "directory");
    if (!dir.exists()) return dir;
    if (dir.isFile()) throw new FatalConfigurationRuntimeException("Invalid persistence directory" + dir + ": must not be a file");
    if (!(dir.canRead() && dir.canWrite())) throw new FatalConfigurationRuntimeException("Invalid persistence directory" + dir + ": " +
            (!dir.canRead() ? "not readable" :
                    (!dir.canWrite() ? "not writable" : "unknown reason")));
    return dir;
}
 
Example 17
Source File: InitializrProjectPanelVisual3.java    From nb-springboot with Apache License 2.0 5 votes vote down vote up
boolean valid(WizardDescriptor wizardDescriptor) {
    if (projectNameTextField.getText().length() == 0) {
        // Display name not specified
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Name is not a valid folder name.");
        return false;
    }
    File f = FileUtil.normalizeFile(new File(projectLocationTextField.getText()).getAbsoluteFile());
    if (!f.isDirectory()) {
        wizardDescriptor.putProperty("WizardPanel_errorMessage", "Project Folder is not a valid path.");
        return false;
    }
    final File destFolder = FileUtil.normalizeFile(new File(createdFolderTextField.getText()).getAbsoluteFile());
    File projLoc = destFolder;
    while (projLoc != null && !projLoc.exists()) {
        projLoc = projLoc.getParentFile();
    }
    if (projLoc == null || !projLoc.canWrite()) {
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Folder cannot be created.");
        return false;
    }
    if (FileUtil.toFileObject(projLoc) == null) {
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Folder is not a valid path.");
        return false;
    }
    File[] kids = destFolder.listFiles();
    if (destFolder.exists() && kids != null && kids.length > 0) {
        // Folder exists and is not empty
        wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "Project Folder already exists and is not empty.");
        return false;
    }
    wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "");
    return true;
}
 
Example 18
Source File: Settings.java    From Local-GSM-Backend with Apache License 2.0 5 votes vote down vote up
public File databaseDirectory() {
    File extDir = new File(preferences.getString(EXTERNAL_DATABASE_LOCATION, ""));

    if (extDir.exists() && extDir.isDirectory() && extDir.canRead() && extDir.canWrite()) {
        return extDir;
    }
    return context.getExternalFilesDir(null);
}
 
Example 19
Source File: FileUtils.java    From gradle-avro-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Opens a {@link FileOutputStream} for the specified file, checking and
 * creating the parent directory if it does not exist.
 * <p>
 * At the end of the method either the stream will be successfully opened,
 * or an exception will have been thrown.
 * <p>
 * The parent directory will be created if it does not exist.
 * The file will be created if it does not exist.
 * An exception is thrown if the file object exists but is a directory.
 * An exception is thrown if the file exists but cannot be written to.
 * An exception is thrown if the parent directory cannot be created.
 *
 * @param file  the file to open for output, must not be <code>null</code>
 * @return a new {@link FileOutputStream} for the specified file
 * @throws IOException if the file object is a directory
 * @throws IOException if the file cannot be written to
 * @throws IOException if a parent directory needs creating but that fails
 * @since Commons IO 1.3
 */
private static FileOutputStream openOutputStream(File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }
        if (!file.canWrite()) {
            throw new IOException("File '" + file + "' cannot be written to");
        }
    } else {
        File parent = file.getParentFile();
        if (parent != null && !parent.exists()) {
            if (!parent.mkdirs()) {
                throw new IOException("File '" + file + "' could not be created");
            }
        }
    }
    return new FileOutputStream(file);
}
 
Example 20
Source File: Desktop.java    From jdk8u60 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Launches the associated editor application and opens a file for
 * editing.
 *
 * @param file the file to be opened for editing
 * @throws NullPointerException if the specified file is {@code null}
 * @throws IllegalArgumentException if the specified file doesn't
 * exist
 * @throws UnsupportedOperationException if the current platform
 * does not support the {@link Desktop.Action#EDIT} action
 * @throws IOException if the specified file has no associated
 * editor, or the associated application fails to be launched
 * @throws SecurityException if a security manager exists and its
 * {@link java.lang.SecurityManager#checkRead(java.lang.String)}
 * method denies read access to the file, or {@link
 * java.lang.SecurityManager#checkWrite(java.lang.String)} method
 * denies write access to the file, or it denies the
 * <code>AWTPermission("showWindowWithoutWarningBanner")</code>
 * permission, or the calling thread is not allowed to create a
 * subprocess
 * @see java.awt.AWTPermission
 */
public void edit(File file) throws IOException {
    checkAWTPermission();
    checkExec();
    checkActionSupport(Action.EDIT);
    file.canWrite();
    checkFileValidation(file);

    peer.edit(file);
}