List of usage examples for java.io File canWrite
public boolean canWrite()
From source file:info.schnatterer.songbirdDbTools.commands.playlist.ExportPlaylistsCommand.java
/** * Checks a path, if it exists, is a directory and if the application can write to it. * /*from w ww . j av a 2 s . c om*/ * @param destinationFolder * the path to be checked. * @throws FileSystemException * if any of the mentioned checks fails. */ private static void checkDirectory(final String destinationFolder) throws FileSystemException { File destinationFile = new File(destinationFolder); if (!destinationFile.exists()) { throw new FileSystemException( "Destination folder does not exist: " + destinationFile.getAbsolutePath()); } if (!destinationFile.isDirectory()) { throw new FileSystemException( "Destination folder is not a directory: " + destinationFile.getAbsolutePath()); } if (!destinationFile.canWrite()) { throw new FileSystemException("Destination folder is read only: " + destinationFile.getAbsolutePath()); } }
From source file:com.jhash.oimadmin.Utils.java
public static void extractJarFile(String directory, String jarFileName) { File baseDir = new File(directory); if (baseDir.exists()) { if (!baseDir.isDirectory()) { throw new InvalidParameterException("Destination directory " + directory + " to expand Jar file " + jarFileName + " is not a directory"); }/*www.j a v a2 s . c o m*/ if (!baseDir.canWrite() || !baseDir.canWrite() || !baseDir.canExecute()) { throw new InvalidParameterException("Destination directory " + directory + " to expand Jar file " + jarFileName + " does not have rwx access for user"); } } else { baseDir.mkdirs(); } try (JarFile jar = new JarFile(jarFileName)) { Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry file = (JarEntry) enumEntries.nextElement(); File f = new File(directory + File.separator + file.getName()); if (file.isDirectory()) { // if its a directory, create it f.mkdirs(); continue; } try (java.io.InputStream is = jar.getInputStream(file); java.io.FileOutputStream fos = new java.io.FileOutputStream(f)) { // get the input stream while (is.available() > 0) { // write contents of 'is' to 'fos' fos.write(is.read()); } fos.close(); is.close(); } catch (Exception exception) { throw new OIMAdminException("Failed to write the jar file entry " + file + " to location " + f, exception); } } } catch (Exception exception) { throw new OIMAdminException("Failed to extract jar file " + jarFileName + " to directory " + directory, exception); } }
From source file:net.naijatek.myalumni.util.utilities.FileUtil.java
/** * Write content to_email a fileName with the destEncoding * // w w w . j a v a 2 s .co m * @param content String * @param fileName String * @param destEncoding String * @throws FileNotFoundException * @throws IOException */ public static void writeFile(final String content, final String fileName, final String destEncoding) throws FileNotFoundException, IOException { File file = null; try { file = new File(fileName); if (file.isFile() == false) { throw new IOException("'" + fileName + "' is not a file."); } if (file.canWrite() == false) { throw new IOException("'" + fileName + "' is a read-only file."); } } finally { // we dont have to close File here } BufferedWriter out = null; try { FileOutputStream fos = new FileOutputStream(fileName); out = new BufferedWriter(new OutputStreamWriter(fos, destEncoding)); out.write(content); out.flush(); } catch (FileNotFoundException fe) { logger.error("Error", fe); throw fe; } catch (IOException e) { logger.error("Error", e); throw e; } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { } } }
From source file:com.meltmedia.cadmium.core.FileSystemManager.java
public static void copyAllContent(final String source, final String target, final boolean ignoreHidden) throws Exception { File sourceFile = new File(source); File targetFile = new File(target); if (!targetFile.exists()) { targetFile.mkdirs();/*from w w w . j a v a 2 s. co m*/ } if (sourceFile.exists() && sourceFile.canRead() && sourceFile.isDirectory() && targetFile.exists() && targetFile.canWrite() && targetFile.isDirectory()) { List<File> copyList = new ArrayList<File>(); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File file, String name) { return !ignoreHidden || !name.startsWith("."); } }; File files[] = sourceFile.listFiles(filter); if (files.length > 0) { copyList.addAll(Arrays.asList(files)); } for (int index = 0; index < copyList.size(); index++) { File aFile = copyList.get(index); String relativePath = aFile.getAbsoluteFile().getAbsolutePath() .replaceFirst(sourceFile.getAbsoluteFile().getAbsolutePath(), ""); if (aFile.isDirectory()) { File newDir = new File(target, relativePath); if (newDir.mkdir()) { newDir.setExecutable(aFile.canExecute(), false); newDir.setReadable(aFile.canRead(), false); newDir.setWritable(aFile.canWrite(), false); newDir.setLastModified(aFile.lastModified()); files = aFile.listFiles(filter); if (files.length > 0) { copyList.addAll(index + 1, Arrays.asList(files)); } } else { log.warn("Failed to create new subdirectory \"{}\" in the target path \"{}\".", relativePath, target); } } else { File newFile = new File(target, relativePath); if (newFile.createNewFile()) { FileInputStream inStream = null; FileOutputStream outStream = null; try { inStream = new FileInputStream(aFile); outStream = new FileOutputStream(newFile); streamCopy(inStream, outStream); } finally { if (inStream != null) { try { inStream.close(); } catch (Exception e) { } } if (outStream != null) { try { outStream.flush(); } catch (Exception e) { } try { outStream.close(); } catch (Exception e) { } } } newFile.setExecutable(aFile.canExecute(), false); newFile.setReadable(aFile.canRead(), false); newFile.setWritable(aFile.canWrite(), false); newFile.setLastModified(aFile.lastModified()); } } } } }
From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java
/** * Persists files streaming state in specified directory or system temp directory. * * @param fileAccessState//from w w w . ja va 2 s. c o m * streamed files access state * @param fileDir * directory to save file * @param streamName * stream name * * @return file containing persisted state * * @throws JAXBException * if parsing fails */ static File writeState(FileAccessState fileAccessState, File fileDir, String streamName) throws JAXBException { if (fileAccessState == null) { return null; } JAXBContext jaxb = JAXBContext.newInstance(FileAccessState.class); final Marshaller marshaller = jaxb.createMarshaller(); File fasFile = null; String fileName = getFileName(streamName); if (fileDir != null) { fasFile = new File(fileDir, fileName); } if (fileDir == null || !fasFile.canWrite()) { fasFile = new File(System.getProperty("java.io.tmpdir"), fileName); } marshaller.marshal(fileAccessState, fasFile); return fasFile; }
From source file:com.docd.purefm.test.CommandLineFileTest.java
private static void testAgainstJavaIoFile(final CommandLineFile genericFile, final File javaFile, final boolean testDate) throws Throwable { assertEquals(javaFile, genericFile.toFile()); assertEquals(javaFile.getName(), genericFile.getName()); assertEquals(javaFile.getAbsolutePath(), genericFile.getAbsolutePath()); assertEquals(javaFile.exists(), genericFile.exists()); assertEquals(javaFile.canRead(), genericFile.canRead()); assertEquals(javaFile.canWrite(), genericFile.canWrite()); assertEquals(javaFile.canExecute(), genericFile.canExecute()); assertEquals(javaFile.getPath(), genericFile.getPath()); assertEquals(javaFile.getParent(), genericFile.getParent()); final File parentFile; final GenericFile genericParentFile = genericFile.getParentFile(); if (genericParentFile == null) { parentFile = null;/*from w w w.j av a 2 s.c o m*/ } else { parentFile = genericParentFile.toFile(); } assertEquals(javaFile.getParentFile(), parentFile); assertEquals(javaFile.length(), genericFile.length()); try { assertEquals(FileUtils.isSymlink(javaFile), genericFile.isSymlink()); } catch (IOException e) { e.printStackTrace(); } try { assertEquals(javaFile.getCanonicalPath(), genericFile.getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } assertEquals(javaFile.length(), genericFile.length()); assertEquals(javaFile.isDirectory(), genericFile.isDirectory()); if (genericFile.isDirectory()) { assertTrue(listedPathsEqual(javaFile.list(), genericFile.list())); assertTrue(listedFilesEqual(javaFile.listFiles(), genericFile.listFiles())); } if (testDate) { assertEquals(PFMTextUtils.humanReadableDate(javaFile.lastModified(), false), PFMTextUtils.humanReadableDate(genericFile.lastModified(), true)); } }
From source file:FileStatus.java
public static void status(String fileName) throws IOException { System.out.println("---" + fileName + "---"); // Construct a File object for the given file. File f = new File(fileName); // See if it actually exists if (!f.exists()) { System.out.println("file not found"); System.out.println(); // Blank line return;//from w w w . j a va2 s . c om } // Print full name System.out.println("Canonical name " + f.getCanonicalPath()); // Print parent directory if possible String p = f.getParent(); if (p != null) { System.out.println("Parent directory: " + p); } // Check if the file is readable if (f.canRead()) { System.out.println("File is readable."); } // Check if the file is writable if (f.canWrite()) { System.out.println("File is writable."); } // Report on the modification time. Date d = new Date(); d.setTime(f.lastModified()); System.out.println("Last modified " + d); // See if file, directory, or other. If file, print size. if (f.isFile()) { // Report on the file's size System.out.println("File size is " + f.length() + " bytes."); } else if (f.isDirectory()) { System.out.println("It's a directory"); } else { System.out.println("I dunno! Neither a file nor a directory!"); } System.out.println(); // blank line between entries }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? /* ww w . j a v a 2s . co m*/ * * @return */ @Deprecated public static String downMedia(String access_token, String msgType, String media_id, String path) { String localFile = null; // SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/"); try { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + media_id; // log.error(path); // ? ? URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); String xx = conn.getHeaderField("Content-disposition"); try { log.debug("===? +==?==" + xx); if (xx == null) { InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String line = null; String result = null; while ((line = reader.readLine()) != null) { if (result == null) { result = line; } else { result += line; } } System.out.println(result); JSONObject dataJson = JSONObject.parseObject(result); return dataJson.getString("errcode"); } } catch (Exception e) { } if (conn.getResponseCode() == 200) { String Content_disposition = conn.getHeaderField("Content-disposition"); InputStream inputStream = conn.getInputStream(); // // ? // Long fileSize = conn.getContentLengthLong(); // + String savePath = path + "/" + msgType; // ?? String fileName = StringUtil.getDateSimpleStr() + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", ""); // File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // ?? if (!saveDirFile.canWrite()) { log.error("??"); throw new Exception(); } // System.out.println("------------------------------------------------"); // ? File file = new File(saveDirFile + "/" + fileName); FileOutputStream outStream = new FileOutputStream(file); int len = -1; byte[] b = new byte[1024]; while ((len = inputStream.read(b)) != -1) { outStream.write(b, 0, len); } outStream.flush(); outStream.close(); inputStream.close(); // ? localFile = fileName; } } catch (Exception e) { log.error("? !", e); } finally { } return localFile; }
From source file:com.thruzero.common.core.utils.FileUtilsExt.java
public static final boolean unzipArchive(final File fromFile, final File toDir) throws IOException { boolean result = false; // assumes error logHelper.logBeginUnzip(fromFile, toDir); ZipFile zipFile = new ZipFile(fromFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); if (!toDir.exists()) { toDir.mkdirs();/*from www .ja v a 2s . c o m*/ logHelper.logProgressCreatedToDir(toDir); } logHelper.logProgressToDirIsWritable(toDir); if (toDir.canWrite()) { while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { File dir = new File( toDir.getAbsolutePath() + EnvironmentHelper.FILE_PATH_SEPARATOR + entry.getName()); if (!dir.exists()) { dir.mkdirs(); logHelper.logProgressFilePathCreated(dir); } } else { File fosz = new File( toDir.getAbsolutePath() + EnvironmentHelper.FILE_PATH_SEPARATOR + entry.getName()); logHelper.logProgressCopyEntry(fosz); File parent = fosz.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fosz)); IOUtils.copy(zipFile.getInputStream(entry), bos); bos.flush(); } } zipFile.close(); result = true; // success } else { logHelper.logFileWriteError(fromFile, null); zipFile.close(); } return result; }
From source file:de.julielab.jtbd.TokenizerApplication.java
/** * Entry point for prediction mode//from w w w. j a va 2 s . c om * * @param args * the command line arguments * @throws IOException */ private static void startPredictionMode(final String[] args) throws IOException { if (args.length != 4) { System.err.println("usage: JTBD p <inDir> <outDir> <model-file>"); System.exit(-1); } final File inDir = new File(args[1]); if (!inDir.isDirectory()) { System.err.println("Error: the specified input directory does not exist."); System.exit(-1); } final File outDir = new File(args[2]); if (!outDir.isDirectory() || !outDir.canWrite()) { System.err.println("Error: the specified output directory does not exist or is not writable."); System.exit(-1); } final String modelFilename = args[3]; doPrediction(inDir, outDir, modelFilename); }