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

/**
 * The static method that does the deletion. Invoked by main(), and designed
 * for use by other programs as well. It first makes sure that the specified
 * file or directory is deleteable before attempting to delete it. If there is
 * a problem, it throws an IllegalArgumentException.
 *///from  w  w w  .jav  a 2s.c  om
public static void delete(String filename) {
    // Create a File object to represent the filename
    File f = new File(filename);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
        fail("Delete: no such file or directory: " + filename);
    if (!f.canWrite())
        fail("Delete: write protected: " + filename);

    // If it is a directory, make sure it is empty
    if (f.isDirectory()) {
        String[] files = f.list();
        if (files.length > 0)
            fail("Delete: directory not empty: " + filename);
    }

    // If we passed all the tests, then attempt to delete it
    boolean success = f.delete();

    // And throw an exception if it didn't work for some (unknown) reason.
    // For example, because of a bug with Java 1.1.1 on Linux,
    // directory deletion always fails
    if (!success)
        fail("Delete: deletion failed");
}

From source file:Main.java

/**
 * /*from w w w . j  a v a 2s .  c  o  m*/
 * @param context
 * @param backupFolder
 * @param db_name
 * @return
 */
public static boolean backupDB(Context context, String backupFolder, String db_name) {
    boolean result = false;

    try {
        String current_date = DateToString(GetToday(), "dd-MM-yyyy");

        File data = Environment.getDataDirectory();
        File sdcard = new File(Environment.getExternalStorageDirectory(), backupFolder + "/");
        sdcard.mkdirs();

        if (sdcard.canWrite()) {
            String currentDBPath = "//data//" + context.getPackageName() + "//databases//" + db_name + "";
            String backupDBPath = "backup_" + db_name + "_" + current_date + ".db";

            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sdcard, backupDBPath);

            if (currentDB.exists()) {
                InputStream input = new FileInputStream(currentDB);
                OutputStream output = new FileOutputStream(backupDB);

                byte[] buffer = new byte[1024];
                int length;

                while ((length = input.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }

                output.flush();
                output.close();
                input.close();

                result = true;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

    return result;
}

From source file:bzstats.chart.AbstractChartFactory.java

/**
 * Utility function to save an image as a PNG file.
 *
 * @param image/*from   ww w. j  av a  2s.co m*/
 *            The image to save.
 * @param filename
 *            The filename to save the image as.
 * @throws BZStatsException
 *             If the file could not be written.
 */
public static final void savePNGImage(BufferedImage image, String filename) throws BzStatsException {

    File outputfile = new File(filename);

    // overwrite
    if (outputfile.exists()) {
        if (outputfile.canWrite()) {
            outputfile.delete();
        } else {
            throw new BzStatsException("Cannot overwrite " + filename);
        }
    }

    boolean filecreated;
    try {
        filecreated = outputfile.createNewFile();
    } catch (IOException e2) {
        throw new BzStatsException("Failed to create file " + filename);
    }

    if (filecreated) {

        OutputStream out = null;
        try {
            out = new FileOutputStream(outputfile);
        } catch (FileNotFoundException e3) {
            throw new BzStatsException("Failed to write to file " + filename);
        }

        SunPNGEncoderAdapter encoder = new SunPNGEncoderAdapter();

        try {
            encoder.encode(image, out);
        } catch (IOException e) {
            throw new BzStatsException("Failed to encode file " + filename);
        } finally {
            try {
                out.close();
            } catch (IOException e1) {
                throw new BzStatsException("Failed to close file " + filename);
            }
        }
    } else {
        throw new BzStatsException("Failed to create file " + filename);
    }

}

From source file:eu.qualimaster.adaptation.platform.ToolBase.java

/**
 * Returns whether <code>file</code> is a directory and accessible.
 * //ww w  . j a  v  a  2 s .c om
 * @param file the file
 * @return <code>true</code> if <code>file</code> is a directory and accessible, <code>false</code> else 
 */
protected static boolean isAccessibleDir(File file) {
    return file.exists() && file.isDirectory() && file.canWrite();
}

From source file:com.newatlanta.appengine.junit.vfs.gae.GaeVfsTestCase.java

public static void assertEquals(File file, FileObject fileObject) throws Exception {
    assertEqualPaths(file, fileObject);/*from www . j  av a2 s . c  om*/
    assertEquals(file.canRead(), fileObject.isReadable());
    assertEquals(file.canWrite(), fileObject.isWriteable());
    assertEquals(file.exists(), fileObject.exists());
    if (file.getParentFile() == null) {
        assertNull(fileObject.getParent());
    } else {
        assertEqualPaths(file.getParentFile(), fileObject.getParent());
    }
    assertEquals(file.isDirectory(), fileObject.getType().hasChildren());
    assertEquals(file.isFile(), fileObject.getType().hasContent());
    assertEquals(file.isHidden(), fileObject.isHidden());
    if (file.isFile()) {
        assertEquals(file.length(), fileObject.getContent().getSize());
    }
    if (file.isDirectory()) { // same children
        File[] childFiles = file.listFiles();
        FileObject[] childObjects = fileObject.getChildren();
        assertEquals(childFiles.length, childObjects.length);
        for (int i = 0; i < childFiles.length; i++) {
            assertEqualPaths(childFiles[i], childObjects[i]);
        }
    }
}

From source file:edu.kit.dama.staging.util.StagingUtils.java

/**
 * Get the temporary directory all transfers. This directory is located in the
 * user home directory under ~/.lsdf/. Within the temporary directory the
 * transfer can store status information or checkpoint data to be able to
 * resume failed transfers./*  ww w.  j a  v  a2s.  c  o m*/
 *
 * @return The transfers temporary directory
 *
 * @throws IOException If there was not set any TID for this transfer or if
 * there are problems getting the user's home directory
 */
public static String getTempDir() throws IOException {
    File userHome = SystemUtils.getUserHome();
    if (userHome == null || !userHome.isDirectory() || !userHome.canRead() || !userHome.canWrite()) {
        throw new IOException("Invalid user home directory '" + userHome + "'");
    }
    return FilenameUtils.concat(userHome.getCanonicalPath(), ".lsdf");
}

From source file:Main.java

static File make_tmpdir(Context context, SQLiteDatabase db) throws Exception {

    File extdir = Environment.getExternalStorageDirectory();
    File tmp_top = new File(extdir, "tmp_LongText");
    if (!tmp_top.exists()) {
        if (!tmp_top.mkdir())
            throw new Exception("cannot create directory: " + tmp_top.getPath());
    }/*from   w  w  w.ja v  a 2 s .  c  o  m*/
    if (!tmp_top.canWrite())
        throw new Exception("missing permission to write to " + tmp_top.getPath());

    File tmpdir;
    Random r = new Random();
    do {
        tmpdir = new File(tmp_top, String.format("%d", r.nextInt()));
    } while (tmpdir.exists());
    if (!tmpdir.mkdir())
        throw new Exception("cannot create directory: " + tmp_top.getPath());
    if (!tmpdir.canWrite())
        throw new Exception("missing permission to write to " + tmp_top.getPath());
    ContentValues v = new ContentValues();
    v.put("pid", Process.myPid());
    v.put("tmpdir", tmpdir.getPath());
    v.put("ctime", System.currentTimeMillis());
    db.insert("tmpdir", null, v);

    return tmpdir;
}

From source file:Main.java

/**
 * @return A map of all storage locations available
 */// w  w  w . j a  v a2s.  c  o m
public static Map<String, File> getAllStorageLocations() {
    Map<String, File> map = new HashMap<String, File>(10);

    List<String> mMounts = new ArrayList<String>(10);
    List<String> mVold = new ArrayList<String>(10);
    mMounts.add("/mnt/sdcard");
    mVold.add("/mnt/sdcard");

    try {
        File mountFile = new File("/proc/mounts");
        if (mountFile.exists()) {
            Scanner scanner = new Scanner(mountFile);
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                if (line.startsWith("/dev/block/vold/")) {
                    String[] lineElements = line.split(" ");
                    String element = lineElements[1];

                    // don't add the default mount path
                    // it's already in the list.
                    if (!element.equals("/mnt/sdcard"))
                        mMounts.add(element);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        File voldFile = new File("/system/etc/vold.fstab");
        if (voldFile.exists()) {
            Scanner scanner = new Scanner(voldFile);
            while (scanner.hasNext()) {
                String line = scanner.nextLine();
                if (line.startsWith("dev_mount")) {
                    String[] lineElements = line.split(" ");
                    String element = lineElements[2];

                    if (element.contains(":"))
                        element = element.substring(0, element.indexOf(":"));
                    if (!element.equals("/mnt/sdcard"))
                        mVold.add(element);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    for (int i = 0; i < mMounts.size(); i++) {
        String mount = mMounts.get(i);
        if (!mVold.contains(mount))
            mMounts.remove(i--);
    }
    mVold.clear();

    List<String> mountHash = new ArrayList<String>(10);

    for (String mount : mMounts) {
        File root = new File(mount);
        if (root.exists() && root.isDirectory() && root.canWrite()) {
            File[] list = root.listFiles();
            String hash = "[";
            if (list != null) {
                for (File f : list) {
                    hash += f.getName().hashCode() + ":" + f.length() + ", ";
                }
            }
            hash += "]";
            if (!mountHash.contains(hash)) {
                String key = SD_CARD + "_" + map.size();
                if (map.size() == 0) {
                    key = SD_CARD;
                } else if (map.size() == 1) {
                    key = EXTERNAL_SD_CARD;
                }
                mountHash.add(hash);
                map.put(key, root);
            }
        }
    }

    mMounts.clear();

    if (map.isEmpty()) {
        map.put(SD_CARD, Environment.getExternalStorageDirectory());
    }
    return map;
}

From source file:OS.java

/**
 * Returns the first readable and writable application data folder appropriate
 * to this OS./*from   ww  w .j  a  v  a 2s .c o  m*/
 */
public static File getAppDataFolder() {
    File[] folders = listAppDataFolders();

    for (int i = 0; i < folders.length; i++) {
        File folder = folders[i];
        if (folder.canRead() && folder.canWrite())
            return folder;
    }

    return null;
}

From source file:OS.java

/**
 * Returns the first readable and writable user data folder appropriate to
 * this OS.//from w ww. j a  va2  s .  c  o m
 */
public static File getUserDataFolder() {
    File[] folders = listUserDataFolders();

    for (int i = 0; i < folders.length; i++) {
        File folder = folders[i];
        if (folder.canRead() && folder.canWrite())
            return folder;
    }

    return null;
}