List of usage examples for java.io File canWrite
public boolean canWrite()
From source file:it.geosolutions.tools.compress.file.reader.TarReader.java
/** * A method to read tar file:/* w w w. j ava 2 s . co m*/ * extract its content to the 'destDir' file (which could be * a directory or a file depending on the srcF file content) * @throws CompressorException */ public static void readTar(File srcF, File destDir) throws Exception { if (destDir == null) throw new IllegalArgumentException("Unable to extract to a null destination dir"); if (!destDir.canWrite() && !destDir.mkdirs()) throw new IllegalArgumentException("Unable to extract to a not writeable destination dir: " + destDir); FileInputStream fis = null; TarArchiveInputStream tis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(srcF); bis = new BufferedInputStream(fis); tis = new TarArchiveInputStream(bis); TarArchiveEntry te = null; while ((te = tis.getNextTarEntry()) != null) { File curr_dest = new File(destDir, te.getName()); if (te.isDirectory()) { // create destination folder if (!curr_dest.exists()) curr_dest.mkdirs(); } else { writeFile(curr_dest, tis); } } } finally { if (tis != null) { try { tis.close(); } catch (IOException ioe) { } } if (bis != null) { try { bis.close(); } catch (IOException ioe) { } } if (fis != null) { try { fis.close(); } catch (IOException ioe) { } } } }
From source file:com.twentyoneechoes.borges.util.Utils.java
public static void backupDatabase(Context ctx) { try {//w w w .j a va2 s . c o m File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "//data//" + ctx.getApplicationContext().getPackageName() + "//databases//borges.db"; String backupDBPath = "borges.db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } catch (Exception e) { Log.i(Utils.class.getSimpleName(), "Unable to backup database"); } }
From source file:org.openjira.jira.utils.LoadImageAsync.java
public static void saveImageToFile(String url, Bitmap bm) { try {/*from w w w .j a va 2 s . c o m*/ File root = Environment.getExternalStorageDirectory(); if (root.canWrite()) { File dir = new File(root, "openjiracache"); dir.mkdir(); File file = new File(dir, url.replace("/", "_").replace(":", "-").replace("?", "_").replace("=", "-")); FileOutputStream os = new FileOutputStream(file); bm.compress(CompressFormat.PNG, 5, os); // Log.v(LOGTAG, "Saved bitmap in " + file.getAbsolutePath()); } } catch (Throwable e) { Log.e(LOGTAG, "Could not write file " + e.getMessage()); } }
From source file:org.openjira.jira.utils.LoadImageAsync.java
public static Bitmap getImageFromFile(String url) { try {/*from www . j ava 2 s. c om*/ File root = Environment.getExternalStorageDirectory(); if (root.canWrite()) { File dir = new File(root, "openjiracache"); dir.mkdir(); File file = new File(dir, url.replace("/", "_").replace(":", "-").replace("?", "_").replace("=", "-")); if (file.exists() && file.length() > 0) { FileInputStream is = new FileInputStream(file); Bitmap bm = BitmapFactory.decodeStream(is); // Log.v(LOGTAG, "Loaded file from " + // file.getAbsolutePath()); WeakReference<Bitmap> ref = new WeakReference<Bitmap>(bm); cachedBitmaps.put(url, ref); return bm; } } } catch (Throwable e) { Log.e(LOGTAG, "Could not read file " + e.getMessage()); } return null; }
From source file:net.sourceforge.ganttproject.gui.options.InterfaceOptionPageProvider.java
private static Pair<Boolean, File> checkLocale(Locale l) { if (Arrays.asList(DateFormat.getAvailableLocales()).contains(l)) { return Pair.create(Boolean.TRUE, null); }//from w w w. ja va 2 s.c o m File extDir = getExtDir(); if (!extDir.exists()) { return Pair.create(Boolean.FALSE, null); } if (!extDir.isDirectory()) { return Pair.create(Boolean.FALSE, null); } if (extDir.canWrite()) { GPLogger.logToLogger("Java extensions directory " + extDir + " is writable"); URL libUrl = InterfaceOptionPageProvider.class.getResource("lib"); if (libUrl != null) { try { File galicianLocaleJar = new File(new File(libUrl.toURI()), "javagalician.jar"); File targetJar = new File(extDir, galicianLocaleJar.getName()); GPLogger.logToLogger("Locale extension " + galicianLocaleJar); if (galicianLocaleJar.exists() && !targetJar.exists()) { GPLogger.logToLogger("Exists. Installing now"); FileUtils.copyFileToDirectory(galicianLocaleJar, extDir); return Pair.create(Boolean.TRUE, extDir); } } catch (IOException e) { GPLogger.log(e); } catch (URISyntaxException e) { GPLogger.log(e); } } return Pair.create(Boolean.FALSE, extDir); } else { GPLogger.logToLogger("Java extensions directory " + extDir + " is not writable"); } return Pair.create(Boolean.FALSE, extDir); }
From source file:gov.nih.nci.cagrid.introduce.servicetools.FilePersistenceHelper.java
/** * Ensures the directory specified exists, is readable and writeable. If the * directory does not exist it is created. * /*from ww w .ja v a 2s . com*/ * @param dir * the directory to create or check the permissions of * @throws IOException * if failed to create the directory or if the directory exists * but has invalid permissions. */ public static synchronized void createStorageDirectory(File dir) throws IOException { if (!dir.exists()) { if (!dir.mkdirs()) { throw new IOException("storDirFailed: " + dir); } } else { if (!dir.canWrite() || !dir.canRead()) { throw new IOException("storDirPerm: " + dir); } } }
From source file:Main.java
/** * Check is a file is writable. Detects write issues on external SD card. * * @param file The file/*w w w. j ava2 s .c o m*/ * @return true if the file is writable. */ public static boolean isWritable(@NonNull final File file) { boolean isExisting = file.exists(); try { FileOutputStream output = new FileOutputStream(file, true); try { output.close(); } catch (IOException e) { // do nothing. } } catch (FileNotFoundException e) { return false; } boolean result = file.canWrite(); // Ensure that file is not created during this process. if (!isExisting) { //noinspection ResultOfMethodCallIgnored file.delete(); } return result; }
From source file:com.priocept.jcr.server.UploadServlet.java
public static void writeToFile(String fileName, InputStream iStream, boolean createDir, String servletRealPath) throws IOException { String me = "FileUtils.WriteToFile"; if (fileName == null) { throw new IOException(me + ": filename is null"); }/* ww w. j a v a 2s.c om*/ if (iStream == null) { throw new IOException(me + ": InputStream is null"); } File theFile = new File(servletRealPath + "temp_files/" + fileName); // Check if a file exists. if (theFile.exists()) { String msg = theFile.isDirectory() ? "directory" : (!theFile.canWrite() ? "not writable" : null); if (msg != null) { throw new IOException(me + ": file '" + fileName + "' is " + msg); } } // Create directory for the file, if requested. if (createDir && theFile.getParentFile() != null) { theFile.getParentFile().mkdirs(); } // Save InputStream to the file. BufferedOutputStream fOut = null; try { fOut = new BufferedOutputStream(new FileOutputStream(theFile)); byte[] buffer = new byte[32 * 1024]; int bytesRead = 0; while ((bytesRead = iStream.read(buffer)) != -1) { fOut.write(buffer, 0, bytesRead); } } catch (Exception e) { throw new IOException(me + " failed, got: " + e.toString()); } finally { close(iStream, fOut); } }
From source file:de.pniehus.odal.App.java
/**S * Parses the command line arguments//from ww w . java 2 s . c o m * * @param args * @param filters * @return */ public static Profile parseArgs(String[] args, List<Filter> filters) { boolean windowsConsole = false; Profile profile = new Profile(filters); Options options = new Options(); Options helpOptions = new Options(); Option profileOption = Option.builder("p").longOpt("profile").hasArg().argName("profile name") .desc("Loads or generates the profile with the given name").build(); if (System.getProperty("os.name").toLowerCase().contains("windows")) { Console console = System.console(); if (console != null) { windowsConsole = true; profileOption.setRequired(true); } } options.addOption(profileOption); options.addOption(Option.builder("url").hasArg().argName("url") .desc("Sets the url of the open directory which will be parsed and downloaded").build()); options.addOption(Option.builder("a").longOpt("select-all").desc( "Downloads all available files (except the ones removed by filters), overrules the corresponding setting if a profile is used") .build()); options.addOption(Option.builder("o").longOpt("outputDir").hasArg().argName("directory path").desc( "Sets the output directory to the given directory, overrules the corresponding setting if a profile is used") .build()); options.addOption(Option.builder("w").longOpt("windows-mode") .desc("Enables the windows console mode on non-windows systems. Requires -url and -p to be used.") .build()); Option helpOption = Option.builder("h").longOpt("help").desc("Displays this help dialog").build(); helpOptions.addOption(helpOption); options.addOption(helpOption); CommandLineParser cliParser = new DefaultParser(); try { CommandLine cmd = cliParser.parse(helpOptions, args, true); if (cmd.getOptions().length == 0) { cmd = cliParser.parse(options, args); if (cmd.hasOption("w")) { windowsConsole = true; if (!cmd.hasOption("p")) { System.out.println("ERROR: The profile option is required for windows mode!"); printHelp(filters, options); } } if (cmd.hasOption("p")) { String profileName = cmd.getOptionValue("p"); File profileFile = new File(profileName + ".odal"); if (profileFile.exists()) { try { profile = Profile.loadProfile(profileName); profile.setUserProfile(true); } catch (IOException e) { System.out.println("An error occured while loading the specified profile!"); } } else { try { Profile.saveProfile(profileName, profile); System.out.println("The profile " + profileFile.getName() + " has been created!"); System.exit(0); } catch (IOException e) { System.out.println("An error occured during the creation of the profile " + profileFile.getName() + " : " + e.getMessage()); System.out.println("Terminating."); System.exit(1); } } } if (cmd.hasOption("a")) { profile.setSelectAll(true); } if (cmd.hasOption("o")) { File out = new File(cmd.getOptionValue("o")); if (out.isDirectory() || out.canWrite()) { profile.setOutputPath(out.getAbsolutePath()); } else { System.out.println(out.getAbsolutePath() + " is not a directory or not writeable!"); System.out.println("Terminating."); System.exit(1); } } if (cmd.hasOption("url")) { profile.setUrl(cmd.getOptionValue("url")); } else if (windowsConsole) { System.out.println("ERROR: The -url argument is required for console use on windows systems."); printHelp(filters, options); System.exit(1); } } else { printHelp(filters, options); System.exit(0); } } catch (ParseException e) { System.out.println("\nUnable to parse command line arguments: " + e.getLocalizedMessage() + "\n"); printHelp(filters, options); System.exit(1); } if (windowsConsole) { profile.setWindowsConsoleMode(true); } return profile; }
From source file:com.jerrellmardis.amphitheatre.util.Utils.java
public static void backupDatabase(Context ctx) { try {//from w w w . j ava 2 s . c om File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "//data//" + ctx.getApplicationContext().getPackageName() + "//databases//amphitheatre.db"; String backupDBPath = "amphitheatre.db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } catch (Exception e) { Log.i(Utils.class.getSimpleName(), "Unable to backup database"); } }