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:CommandLineInterpreter.java

/**
 *
 *
 * @param file// ww  w .  j  a  va2 s  .  co m
 * @param guiAlert
 * @return
 */
public static boolean checkResources(final File file, final boolean guiAlert) {
    Scanner input = null;
    String message = null;
    try {
        input = new Scanner(file);
        while (input.hasNextLine()) {
            String currentFilePath = input.nextLine().trim();
            if (!currentFilePath.isEmpty()) {
                File currentFile = new File(currentFilePath);
                if (!currentFile.exists() || !currentFile.canRead() || !currentFile.canWrite()) {
                    message = "Can not read/write resource file:\n\"" + currentFile.getAbsolutePath() + "\"";
                    alert(message, guiAlert);
                    return false;
                }
            }
        }
    } catch (Exception e) {
        // TODO: logging
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
    }

    return true;
}

From source file:Main.java

public static List<String> getExtSDCardPaths() {
    List<String> paths = new ArrayList<String>();
    String extFileStatus = Environment.getExternalStorageState();
    File extFile = Environment.getExternalStorageDirectory();
    if (extFileStatus.endsWith(Environment.MEDIA_UNMOUNTED) && extFile.exists() && extFile.isDirectory()
            && extFile.canWrite()) {
        paths.add(extFile.getAbsolutePath());
    }/* w  w w .  ja va  2s .  c o  m*/
    try {
        // obtain executed result of command line code of 'mount', to judge
        // whether tfCard exists by the result
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("mount");
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        int mountPathIndex = 1;
        while ((line = br.readLine()) != null) {
            // format of sdcard file system: vfat/fuse
            if ((!line.contains("fat") && !line.contains("fuse") && !line.contains("storage"))
                    || line.contains("secure") || line.contains("asec") || line.contains("firmware")
                    || line.contains("shell") || line.contains("obb") || line.contains("legacy")
                    || line.contains("data")) {
                continue;
            }
            String[] parts = line.split(" ");
            int length = parts.length;
            if (mountPathIndex >= length) {
                continue;
            }
            String mountPath = parts[mountPathIndex];
            if (!mountPath.contains("/") || mountPath.contains("data") || mountPath.contains("Data")) {
                continue;
            }
            File mountRoot = new File(mountPath);
            if (!mountRoot.exists() || !mountRoot.isDirectory() || !mountRoot.canWrite()) {
                continue;
            }
            boolean equalsToPrimarySD = mountPath.equals(extFile.getAbsolutePath());
            if (equalsToPrimarySD) {
                continue;
            }
            paths.add(mountPath);
        }
    } catch (IOException e) {
        Log.e(TAG, "IOException:" + e.getMessage());
    }
    return paths;
}

From source file:com.clustercontrol.collect.util.ZipCompresser.java

/**
 * ?????1????/*from  w  w w.  jav  a 2 s .  c o m*/
 * 
 * @param inputFileNameList ??
 * @param outputFileName ?
 * 
 * @return ???
 */
protected static synchronized void archive(ArrayList<String> inputFileNameList, String outputFileName)
        throws HinemosUnknown {
    m_log.debug("archive() output file = " + outputFileName);

    byte[] buf = new byte[128];
    BufferedInputStream in = null;
    ZipEntry entry = null;
    ZipOutputStream out = null;

    // ?
    if (outputFileName == null || "".equals(outputFileName)) {
        HinemosUnknown e = new HinemosUnknown("archive output fileName is null ");
        m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    }
    File zipFile = new File(outputFileName);
    if (zipFile.exists()) {
        if (zipFile.isFile() && zipFile.canWrite()) {
            m_log.debug("archive() output file = " + outputFileName
                    + " is exists & file & writable. initialize file(delete)");
            if (!zipFile.delete())
                m_log.debug("Fail to delete " + zipFile.getAbsolutePath());
        } else {
            HinemosUnknown e = new HinemosUnknown("archive output fileName is directory or not writable ");
            m_log.info("archive() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
            throw e;
        }
    }

    // ?
    try {
        // ????
        out = new ZipOutputStream(new FileOutputStream(outputFileName));

        for (String inputFileName : inputFileNameList) {
            m_log.debug("archive() input file name = " + inputFileName);

            // ????
            in = new BufferedInputStream(new FileInputStream(inputFileName));

            // ??
            String fileName = (new File(inputFileName)).getName();
            m_log.debug("archive() entry file name = " + fileName);
            entry = new ZipEntry(fileName);

            out.putNextEntry(entry);
            // ????
            int size;
            while ((size = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, size);
            }
            // ??
            out.closeEntry();
            in.close();
        }
        // ? out.flush();
        out.close();

    } catch (IOException e) {
        m_log.warn("archive() archive error : " + outputFileName + e.getClass().getSimpleName() + ", "
                + e.getMessage(), e);
        throw new HinemosUnknown("archive error " + outputFileName, e);

    } finally {

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.rom.jmultipatcher.Utils.java

public static void checkFilePermissions(final String filepath, final boolean canRead, final boolean canWrite) {
    final Path path = Paths.get(filepath);
    final File file = path.toFile();
    if (canRead && !file.canRead()) {
        throw new IllegalArgumentException("Can't read file" + filepath);
    }/*  w  w w. j  a v  a  2s.  c o  m*/
    if (canWrite && !file.canWrite()) {
        throw new IllegalArgumentException("Can't write to file" + filepath);
    }
}

From source file:edu.monash.merc.util.file.DMFileUtils.java

public static boolean checkWritePermission(String pathName) {
    if (pathName == null) {
        throw new DMFileException("directory name must not be null");
    }/*w w w .j  a v  a 2 s  .  c o  m*/
    try {
        File dir = new File(pathName);
        return dir.canWrite();
    } catch (Exception e) {
        logger.error(e.getMessage());
        return false;
    }
}

From source file:Dialogs.java

private static boolean canSaveToFile(Frame parentFrame, File outFile) {
    if (!outFile.exists()) {
        return true;
    }/*ww  w .  j  a  v  a  2 s . c om*/
    String msg = "Alreadyexists" + outFile.getAbsolutePath();
    if (!Dialogs.showYesNo(parentFrame, msg)) {
        return false;
    }
    if (!outFile.canWrite()) {
        msg = "Cannotwrite" + outFile.getAbsolutePath();
        Dialogs.showOk(parentFrame, msg);
        return false;
    }
    outFile.delete();
    return true;
}

From source file:com.dnielfe.manager.dialogs.DirectoryInfoDialog.java

private static String getFilePermissions(File file) {
    String per = "";

    per += file.isDirectory() ? "d" : "-";
    per += file.canRead() ? "r" : "-";
    per += file.canWrite() ? "w" : "-";
    per += file.canExecute() ? "x" : "-";

    return per;//from  w w  w.java 2s .  c  o  m
}

From source file:Main.java

/**
 * Opens a {@link FileOutputStream} for the specified file, checking and
 * creating the parent directory if it does not exist.
 * <p>//from w ww.  j  av a  2s.co  m
 * 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>
 * @param append if <code>true</code>, then bytes will be added to the
 * end of the file rather than overwriting
 * @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 2.1
 */
public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }
        if (file.canWrite() == false) {
            throw new IOException("File '" + file + "' cannot be written to");
        }
    } else {
        File parent = file.getParentFile();
        if (parent != null) {
            if (!parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("Directory '" + parent + "' could not be created");
            }
        }
    }
    return new FileOutputStream(file, append);
}

From source file:com.manydesigns.elements.util.ElementsFileUtils.java

public static boolean ensureDirectoryExistsAndWritable(File file) {
    logger.debug("Ensure directory exists and writable: {}", file);
    if (!ensureDirectoryExists(file))
        return false;
    if (!file.canWrite()) {
        logger.warn("Directory not writable: {}", file);
        return false;
    } else {/*from w w w .  j a  v a 2s .c om*/
        logger.debug("Success");
        return true;
    }
}

From source file:fr.romainf.QRCode.java

/**
 * Writes data as a QRCode in an image.//  ww  w .j  a va 2 s  .c  om
 *
 * @param data        String The data to encode in a QRCode
 * @param output      String The output filename
 * @param pixelColour Color The colour of pixels representing bits
 * @throws WriterException
 * @throws IOException
 */
private static void writeQRCode(String data, String output, Color pixelColour)
        throws WriterException, IOException {
    Map<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
    hints.put(EncodeHintType.MARGIN, DEFAULT_MARGIN);

    BitMatrix bitMatrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, DEFAULT_WIDTH, DEFAULT_HEIGHT,
            hints);

    File file = new File(output);
    if (file.isDirectory()) {
        file = new File(output + File.separator + DEFAULT_OUTPUT_FILE);
    }
    if (!file.createNewFile() && !file.canWrite()) {
        throw new IOException("Cannot write file " + file);
    }

    SVGGraphics2D graphics2D = renderSVG(bitMatrix, pixelColour);
    graphics2D.stream(new FileWriter(file), true);
}