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:net.idlesoft.android.apps.github.activities.SingleActivityItem.java

public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case 0://from w  w w.  j  a va  2 s  .  com
        final Intent i1 = new Intent(this, Hubroid.class);
        startActivity(i1);
        return true;
    case 1:
        mEditor.clear().commit();
        final Intent intent = new Intent(this, Hubroid.class);
        startActivity(intent);
        return true;
    case 2:
        final File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()) {
            final File hubroid = new File(root, "hubroid");
            if (!hubroid.exists() && !hubroid.isDirectory()) {
                return true;
            } else {
                hubroid.delete();
                return true;
            }
        }
    }
    return false;
}

From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

private void dumpToFile(URL url) {
    File externalStorage = Environment.getExternalStorageDirectory();
    if (!externalStorage.canWrite())
        return;/*from   w w  w  . jav  a2  s .c  o  m*/

    String fn = null;

    String[] f = url.toString().split("/");
    fn = f[f.length - 1].split("\\?")[0];
    Log.w("--------------", fn);

    String base = String.format("%s/dreamDroid/xml", externalStorage);
    File file = new File(String.format("%s/%s", base, fn));
    BufferedOutputStream bos = null;
    try {
        (new File(base)).mkdirs();
        file.createNewFile();
        bos = new BufferedOutputStream(new FileOutputStream(file));
        bos.write(mBytes);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:net.idlesoft.android.apps.github.activities.Repository.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case 3://  www .  ja  v a  2 s .  co  m
        try {
            JSONObject newRepoInfo = null;
            if (mIsWatching) {
                final Response unwatchResp = mGapi.repo.unwatch(mRepositoryOwner, mRepositoryName);
                if (unwatchResp.statusCode == 200) {
                    newRepoInfo = new JSONObject(unwatchResp.resp).getJSONObject("repository");
                    mIsWatching = false;
                }
            } else {
                final Response watchResp = mGapi.repo.watch(mRepositoryOwner, mRepositoryName);
                if (watchResp.statusCode == 200) {
                    newRepoInfo = new JSONObject(watchResp.resp).getJSONObject("repository");
                    mIsWatching = true;
                }
            }
            if (newRepoInfo != null) {
                final String newWatcherCount = newRepoInfo.getString("watchers");
                if (newWatcherCount != mJson.getString("watchers")) {
                    if (newWatcherCount == "1") {
                        ((TextView) findViewById(R.id.tv_repository_info_watchers))
                                .setText(newWatcherCount + " watcher");
                    } else {
                        ((TextView) findViewById(R.id.tv_repository_info_watchers))
                                .setText(newWatcherCount + " watchers");
                    }
                }
            }
        } catch (final JSONException e) {
            e.printStackTrace();
        }
        break;
    case 0:
        final Intent i1 = new Intent(this, Hubroid.class);
        startActivity(i1);
        return true;
    case 1:
        mEditor.clear().commit();
        final Intent intent = new Intent(this, Hubroid.class);
        startActivity(intent);
        return true;
    case 2:
        final File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()) {
            final File hubroid = new File(root, "hubroid");
            if (!hubroid.exists() && !hubroid.isDirectory()) {
                return true;
            } else {
                hubroid.delete();
                return true;
            }
        }
    }
    return false;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.cache.SequencePersistingCache.java

@Override
public CachedVersionable put(final String id, final Sequence obj) throws IOException {
    String key = null;//www  .  j a va2s.c o m
    checkArgument(
            isNotBlank(key = toKey(id)) && obj != null && isNotBlank(obj.getId())
                    && isNotBlank(obj.getVersion()) && obj.getSequence() != null,
            "Uninitialized or invalid sequence");
    File outfile = null;
    try {
        final String uuid = randomUUID().toString();
        outfile = new File(new File(getCacheDir(), uuid.substring(0, 2)), uuid);
        final File parentDir = outfile.getParentFile();
        if (parentDir.exists() || parentDir.mkdirs())
            ;
        if ((outfile.isFile() && outfile.canWrite()) || outfile.createNewFile())
            ;
        final CachedVersionable cached = CachedVersionable.builder().cachedFilename(outfile.getCanonicalPath())
                .version(obj.getVersion().trim()).build();
        GBSEQ_XMLB.typeToFile(obj.getSequence(), outfile);
        CACHE.put(key, cached);
        return cached;
    } catch (Exception e) {
        deleteQuietly(outfile);
        throw e;
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

private boolean isProtected(Path path) {
    File file = path.toFile();
    return !(file.canRead() && file.canWrite());
}

From source file:io.smartspaces.util.io.directorywatcher.SimpleDirectoryWatcher.java

@Override
public synchronized void addDirectory(File directory) {
    if (directory.isDirectory()) {
        if (directory.canRead()) {
            if (directory.canWrite()) {
                if (cleanFirst) {
                    fileSupport.deleteDirectoryContents(directory);
                }/*  www.  j  av a 2 s .  co m*/
            }
            directoriesWatched.add(directory);
        } else {
            throw new IllegalArgumentException(String.format("%s is not readable", directory));
        }
    } else if (directory.exists()) {
        // The file exists, but it isn't a directory.
        //
        // This is checked for separately to handle directories added
        // after the watcher starts running.
        throw new IllegalArgumentException(String.format("%s is not a directory", directory));
    } else {
        // Assume the directory will be added at some point
        directoriesWatched.add(directory);
    }
}

From source file:com.predic8.membrane.core.interceptor.statistics.StatisticsCSVInterceptor.java

private void createCSVFile() throws Exception {
    synchronized (fileName) {
        File csvFile = new File(fileName);
        log.debug("creating csv file at " + csvFile.getAbsolutePath());

        if (csvFile.getParentFile() != null) {
            csvFile.getParentFile().mkdirs();
        }/*w w  w  .ja v  a  2  s  .c  om*/
        csvFile.createNewFile();

        if (!csvFile.canWrite())
            throw new IOException("File " + fileName + " is not writable.");

        if (csvFile.length() == 0)
            writeHeaders();
    }
}

From source file:eu.stratosphere.nephele.io.channels.FileBufferManager.java

/**
 * Constructs a new file buffer manager object.
 */// w  w w .  ja  va 2s .  c o m
private FileBufferManager() {

    this.tmpDirs = GlobalConfiguration
            .getString(ConfigConstants.TASK_MANAGER_TMP_DIR_KEY, ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH)
            .split(File.pathSeparator);

    // check temp dirs
    for (int i = 0; i < this.tmpDirs.length; i++) {
        File f = new File(this.tmpDirs[i]);
        if (!(f.exists() && f.isDirectory() && f.canWrite())) {
            LOG.error("Temp directory '" + f.getAbsolutePath() + "' is not a writable directory. "
                    + "Replacing path with default temp directory: "
                    + ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH);
            this.tmpDirs[i] = ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH;
        }
        this.tmpDirs[i] = this.tmpDirs[i] + File.separator + FILE_BUFFER_PREFIX;
    }

    this.bufferSize = GlobalConfiguration.getInteger("channel.network.bufferSizeInBytes", 64 * 1024); // TODO: Use
    // config
    // constants
    // here

    this.fileMap = new ConcurrentHashMap<AbstractID, ChannelWithAccessInfo>(2048, 0.8f, 64);

    this.distributedTempPath = CheckpointUtils.getDistributedCheckpointPath();
    FileSystem distFS = null;
    if (this.distributedTempPath != null && CheckpointUtils.allowDistributedCheckpoints()) {

        try {

            distFS = this.distributedTempPath.getFileSystem();
            if (!distFS.exists(this.distributedTempPath)) {
                distFS.mkdirs(this.distributedTempPath);
            }

        } catch (IOException e) {
            LOG.error(StringUtils.stringifyException(e));
        }
    }

    this.distributedFileSystem = distFS;
}

From source file:com.adaptris.fs.StandardWorkerTest.java

@Test
public void testListFilesWith_NullResponse() throws Exception {
    File dir = Mockito.mock(File.class);
    Mockito.when(dir.canWrite()).thenReturn(true);
    Mockito.when(dir.exists()).thenReturn(true);
    Mockito.when(dir.canRead()).thenReturn(true);
    Mockito.when(dir.isDirectory()).thenReturn(true);
    Mockito.when(dir.listFiles((FileFilter) Mockito.any())).thenReturn(null);
    StandardWorker worker = createWorker();
    try {/*from  w  w  w  . jav  a2 s.  co m*/
        worker.listFiles(dir);
        fail();
    } catch (FsException expected) {

    }
}

From source file:com.cloudant.sync.datastore.DatastoreManager.java

/**
 * <p>Constructs a {@code DatastoreManager} to manage a directory.</p>
 *
 * <p>Datastores are created within the {@code directoryPath} directory.
 * In general, this folder should be under the control of, and only used
 * by, a single {@code DatastoreManager} object at any time.</p>
 *
 * @param directoryPath root directory to manage
 *
 * @throws IllegalArgumentException if the {@code directoryPath} is not a
 *          directory or isn't writable.
 *//*www  .  j av a  2  s . c o m*/
public DatastoreManager(File directoryPath) {
    Log.d(LOG_TAG, "Datastore path: " + directoryPath);
    if (!directoryPath.isDirectory()) {
        throw new IllegalArgumentException("Input path is not a valid directory");
    } else if (!directoryPath.canWrite()) {
        throw new IllegalArgumentException("Datastore directory is not writable");
    }
    this.path = directoryPath.getAbsolutePath();
}