List of usage examples for java.io File canRead
public boolean canRead()
From source file:eu.annocultor.common.Utils.java
public static List<File> expandFileTemplateFrom(File dir, String... pattern) throws IOException { List<File> files = new ArrayList<File>(); for (String p : pattern) { File fdir = new File(new File(dir, FilenameUtils.getFullPathNoEndSeparator(p)).getCanonicalPath()); if (!fdir.isDirectory()) throw new IOException("Error: " + fdir.getCanonicalPath() + ", expanded from directory " + dir.getCanonicalPath() + " and pattern " + p + " does not denote a directory"); if (!fdir.canRead()) throw new IOException("Error: " + fdir.getCanonicalPath() + " is not readable"); FileFilter fileFilter = new WildcardFileFilter(FilenameUtils.getName(p)); File[] list = fdir.listFiles(fileFilter); if (list == null) throw new IOException("Error: " + fdir.getCanonicalPath() + " does not denote a directory or something else is wrong"); if (list.length == 0) throw new IOException("Error: no files found, template " + p + " from dir " + dir.getCanonicalPath() + " where we recognised " + fdir.getCanonicalPath() + " as path and " + fileFilter + " as file mask"); for (File file : list) { if (!file.exists()) { throw new FileNotFoundException( "File not found: " + file + " resolved to " + file.getCanonicalPath()); }/*from w w w. j a v a 2 s. co m*/ } files.addAll(Arrays.asList(list)); } return files; }
From source file:gov.nasa.ensemble.common.io.FileUtilities.java
/** * This function will copy files or directories from one location to another. note that the source and the destination must be mutually exclusive. This function can not be used to copy a directory * to a sub directory of itself. The function will also have problems if the destination files already exist. * //from ww w . j av a 2s . c o m * @param src * -- A File object that represents the source for the copy * @param dest * -- A File object that represnts the destination for the copy. * @throws IOException * if unable to copy. */ public static void copyFiles(File src, File dest) throws IOException { // Check to ensure that the source is valid... if (!src.exists()) { throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + "."); } else if (!src.canRead()) { // check to ensure we have rights to the source... throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + "."); } // is this a directory copy? if (src.isDirectory()) { if (!dest.exists()) { // does the destination already exist? // if not we need to make it exist if possible (note this is mkdirs not mkdir) if (!dest.mkdirs()) { throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + "."); } } // get a listing of files... String list[] = src.list(); // copy all the files in the list. for (int i = 0; i < list.length; i++) { File dest1 = new File(dest, list[i]); File src1 = new File(src, list[i]); copyFiles(src1, dest1); } } else { // This was not a directory, so lets just copy the file FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; // Buffer 4K at a time (you can change this). int bytesRead; try { // open the files for input and output fin = new FileInputStream(src); fout = new FileOutputStream(dest); // while bytesRead indicates a successful read, lets write... while ((bytesRead = fin.read(buffer)) >= 0) { fout.write(buffer, 0, bytesRead); } } catch (IOException e) { // Error copying file... IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath() + "to" + dest.getAbsolutePath() + "."); wrapper.initCause(e); wrapper.setStackTrace(e.getStackTrace()); throw wrapper; } finally { // Ensure that the files are closed (if they were open). if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } } }
From source file:kr.co.leem.system.FileSystemUtils.java
/** * ? ? ? ./*from ww w . j av a2 s . co m*/ * * @param path ? ? . * @return ? ? true. * @see File#canRead() */ public static boolean canRead(String path) { boolean check = false; try { File checkFile = new File(path); if (checkFile.exists()) { check = checkFile.canRead(); } } catch (SecurityException e) { check = false; } return check; }
From source file:gridool.util.xfer.TransferUtils.java
public static void sendfile(@Nonnull final File file, final long fromPos, final long count, @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort, final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler) throws IOException { if (!file.exists()) { throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist"); }//from w ww . j a v a2 s .com if (!file.isFile()) { throw new IllegalArgumentException(file.getAbsolutePath() + " is not file"); } if (!file.canRead()) { throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read"); } final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort); SocketChannel channel = null; Socket socket = null; final OutputStream out; try { channel = SocketChannel.open(); socket = channel.socket(); socket.connect(dstSockAddr); out = socket.getOutputStream(); } catch (IOException e) { LOG.error("failed to connect: " + dstSockAddr, e); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); throw e; } DataInputStream din = null; if (sync) { InputStream in = socket.getInputStream(); din = new DataInputStream(in); } final DataOutputStream dos = new DataOutputStream(out); final StopWatch sw = new StopWatch(); FileInputStream src = null; final long nbytes; try { src = new FileInputStream(file); FileChannel fc = src.getChannel(); String fileName = file.getName(); IOUtils.writeString(fileName, dos); IOUtils.writeString(writeDirPath, dos); long xferBytes = (count == -1L) ? fc.size() : count; dos.writeLong(xferBytes); dos.writeBoolean(append); // append=false dos.writeBoolean(sync); if (handler == null) { dos.writeBoolean(false); } else { dos.writeBoolean(true); handler.writeAdditionalHeader(dos); } // send file using zero-copy send nbytes = fc.transferTo(fromPos, xferBytes, channel); if (LOG.isDebugEnabled()) { LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to " + dstSockAddr.toString() + " in " + sw.toString()); } if (sync) {// receive ack in sync mode long remoteRecieved = din.readLong(); if (remoteRecieved != xferBytes) { throw new IllegalStateException( "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes"); } } } catch (FileNotFoundException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } finally { IOUtils.closeQuietly(src); IOUtils.closeQuietly(din, dos); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); } }
From source file:edu.internet2.middleware.psp.util.PSPUtil.java
/** * Returns {@link Resource}s with the given names. If the path is {@code null}, resources will be found using the * classpath./* w w w . j av a 2 s. co m*/ * * @param path the directory containing resources * @param resourceNames the names of the resource files * @return the resources * @throws ResourceException if an error occurs loading the resource * @throws IllegalArgumentException if the resources are not files or are not readable */ public static List<Resource> getResources(String path, String... resourceNames) throws ResourceException { ArrayList<Resource> resources = new ArrayList<Resource>(); for (String resourceName : resourceNames) { File file = null; if (path == null) { file = PSPUtil.getFile(resourceName); } else { file = new File(path + System.getProperty("file.separator") + resourceName); } if (file == null) { throw new IllegalArgumentException("Unable to find file '" + resourceName + "'."); } if (!file.isFile() || !file.canRead()) { throw new IllegalArgumentException("Unable to read file '" + resourceName + "'."); } resources.add(new FilesystemResource(file.getAbsolutePath())); } return resources; }
From source file:com.floragunn.searchguard.util.SecurityUtil.java
public static File getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) { File jaasConfigFile = null; final URL jaasConfigURL = SecurityUtil.class.getClassLoader().getResource(fileNameFromClasspath); if (jaasConfigURL != null) { try {/*from w w w .ja v a2 s. c om*/ jaasConfigFile = new File(URLDecoder.decode(jaasConfigURL.getFile(), "UTF-8")); } catch (final UnsupportedEncodingException e) { return null; } if (jaasConfigFile.exists() && jaasConfigFile.canRead()) { return jaasConfigFile; } else { log.error("Cannot read from {}, maybe the file does not exists? ", jaasConfigFile.getAbsolutePath()); } } else { log.error("Failed to load " + fileNameFromClasspath); } return null; }
From source file:edu.kit.dama.ui.commons.util.UIUtils7.java
public static void openResourceSubWindow(File sourceFile) { boolean fileAccessible = sourceFile != null && sourceFile.exists() && sourceFile.canRead(); // Set subwindow for displaying file resource final Window window = new Window(fileAccessible ? sourceFile.getName() : "Information"); window.center();/* w w w . j a v a2 s . c o m*/ // Set window layout VerticalLayout windowLayout = new VerticalLayout(); windowLayout.setSizeFull(); if (fileAccessible) { // Set resource that has to be embedded final Embedded resource = new Embedded(null, new FileResource(sourceFile)); if ("application/octet-stream".equals(resource.getMimeType())) { window.setWidth("570px"); window.setHeight("150px"); windowLayout.setMargin(true); Label attentionNote = new Label( "A file preview is not possible as the file type is not supported by your browser."); attentionNote.setContentMode(ContentMode.HTML); Link fileURL = new Link("Click here for downloading the file.", new FileResource(sourceFile)); windowLayout.addComponent(attentionNote); windowLayout.addComponent(fileURL); windowLayout.setComponentAlignment(attentionNote, Alignment.MIDDLE_CENTER); windowLayout.setComponentAlignment(fileURL, Alignment.MIDDLE_CENTER); } else { window.setResizable(true); window.setWidth("800px"); window.setHeight("500px"); final Image image = new Image(null, new FileResource(sourceFile)); image.setSizeFull(); windowLayout.addComponent(image); } } else { //file is not accessible window.setWidth("570px"); window.setHeight("150px"); windowLayout.setMargin(true); Label attentionNote = new Label("Provided file cannot be accessed."); attentionNote.setContentMode(ContentMode.HTML); windowLayout.addComponent(attentionNote); windowLayout.setComponentAlignment(attentionNote, Alignment.MIDDLE_CENTER); } window.setContent(windowLayout); UI.getCurrent().addWindow(window); }
From source file:com.joyent.manta.config.ConfigContext.java
/** * Utility method for validating that the client-side encryption * configuration has been instantiated with valid settings. * * @param config configuration to test/*w w w .j a v a 2 s. c o m*/ * @param failureMessages list of messages to present the user for validation failures * @throws ConfigurationException thrown when validation fails */ static void encryptionSettings(final ConfigContext config, final List<String> failureMessages) { // KEY ID VALIDATIONS if (config.getEncryptionKeyId() == null) { failureMessages.add("Encryption key id must not be null"); } if (config.getEncryptionKeyId() != null && StringUtils.isEmpty(config.getEncryptionKeyId())) { failureMessages.add("Encryption key id must not be empty"); } if (config.getEncryptionKeyId() != null && StringUtils.containsWhitespace(config.getEncryptionKeyId())) { failureMessages.add("Encryption key id must not contain whitespace"); } if (config.getEncryptionKeyId() != null && !StringUtils.isAsciiPrintable(config.getEncryptionKeyId())) { failureMessages.add(("Encryption key id must only contain printable ASCII characters")); } // AUTHENTICATION MODE VALIDATIONS if (config.getEncryptionAuthenticationMode() == null) { failureMessages.add("Encryption authentication mode must not be null"); } // PERMIT UNENCRYPTED DOWNLOADS VALIDATIONS if (config.permitUnencryptedDownloads() == null) { failureMessages.add("Permit unencrypted downloads flag must not be null"); } // PRIVATE KEY VALIDATIONS if (config.getEncryptionPrivateKeyPath() == null && config.getEncryptionPrivateKeyBytes() == null) { failureMessages.add("Both encryption private key path and private key bytes must not be null"); } if (config.getEncryptionPrivateKeyPath() != null && config.getEncryptionPrivateKeyBytes() != null) { failureMessages.add("Both encryption private key path and private key bytes must " + "not be set. Choose one or the other."); } if (config.getEncryptionPrivateKeyPath() != null) { File keyFile = new File(config.getEncryptionPrivateKeyPath()); if (!keyFile.exists()) { failureMessages.add(String.format("Key file couldn't be found at path: %s", config.getEncryptionPrivateKeyPath())); } else if (!keyFile.canRead()) { failureMessages.add(String.format("Key file couldn't be read at path: %s", config.getEncryptionPrivateKeyPath())); } } if (config.getEncryptionPrivateKeyBytes() != null) { if (config.getEncryptionPrivateKeyBytes().length == 0) { failureMessages.add("Encryption private key byte length must be greater than zero"); } } // CIPHER ALGORITHM VALIDATIONS final String algorithm = config.getEncryptionAlgorithm(); if (algorithm == null) { failureMessages.add("Encryption algorithm must not be null"); } if (algorithm != null && StringUtils.isBlank(algorithm)) { failureMessages.add("Encryption algorithm must not be blank"); } if (algorithm != null && !SupportedCiphersLookupMap.INSTANCE.containsKeyCaseInsensitive(algorithm)) { String availableAlgorithms = StringUtils.join(SupportedCiphersLookupMap.INSTANCE.keySet(), ", "); failureMessages.add(String.format( "Cipher algorithm [%s] was not found among " + "the list of supported algorithms [%s]", algorithm, availableAlgorithms)); } }
From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java
private static void forceUpdate() throws IOException, VcdiffDecodeException { File backupFile = new File(DATA_DIR, "helios.jar.bak"); try {//from www . ja v a2 s . c o m Files.copy(IMPL_FILE.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException exception) { // We're going to wrap it so end users know what went wrong throw new IOException(String.format("Could not back up Helios implementation (%s %s, %s %s)", IMPL_FILE.canRead(), IMPL_FILE.canWrite(), backupFile.canRead(), backupFile.canWrite()), exception); } URL latestVersion = new URL("https://ci.samczsun.com/job/Helios/lastStableBuild/buildNumber"); HttpURLConnection connection = (HttpURLConnection) latestVersion.openConnection(); if (connection.getResponseCode() == 200) { boolean aborted = false; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(connection.getInputStream(), outputStream); String version = new String(outputStream.toByteArray(), "UTF-8"); System.out.println("Latest version: " + version); int intVersion = Integer.parseInt(version); loop: while (true) { int buildNumber = loadHelios().buildNumber; int oldBuildNumber = buildNumber; System.out.println("Current Helios version is " + buildNumber); if (buildNumber < intVersion) { while (buildNumber <= intVersion) { buildNumber++; URL status = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/api/json"); HttpURLConnection con = (HttpURLConnection) status.openConnection(); if (con.getResponseCode() == 200) { JsonObject object = Json.parse(new InputStreamReader(con.getInputStream())).asObject(); if (object.get("result").asString().equals("SUCCESS")) { JsonArray artifacts = object.get("artifacts").asArray(); for (JsonValue value : artifacts.values()) { JsonObject artifact = value.asObject(); String name = artifact.get("fileName").asString(); if (name.contains("helios-") && !name.contains(IMPLEMENTATION_VERSION)) { JOptionPane.showMessageDialog(null, "Bootstrapper is out of date. Patching cannot continue"); aborted = true; break loop; } } URL url = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/artifact/target/delta.patch"); con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() == 200) { File dest = new File(DATA_DIR, "delta.patch"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); copy(con.getInputStream(), byteArrayOutputStream); FileOutputStream fileOutputStream = new FileOutputStream(dest); fileOutputStream.write(byteArrayOutputStream.toByteArray()); fileOutputStream.close(); File cur = IMPL_FILE; File old = new File(IMPL_FILE.getAbsolutePath() + "." + oldBuildNumber); if (cur.renameTo(old)) { VcdiffDecoder.decode(old, dest, cur); old.delete(); dest.delete(); continue loop; } else { throw new IllegalArgumentException("Could not rename"); } } } } else { JOptionPane.showMessageDialog(null, "Server returned response code " + con.getResponseCode() + " " + con.getResponseMessage() + "\nAborting patch process", null, JOptionPane.INFORMATION_MESSAGE); aborted = true; break loop; } } } else { break; } } if (!aborted) { int buildNumber = loadHelios().buildNumber; System.out.println("Running Helios version " + buildNumber); JOptionPane.showMessageDialog(null, "Updated Helios to version " + buildNumber + "!"); Runtime.getRuntime().exec(new String[] { "java", "-jar", BOOTSTRAPPER_FILE.getAbsolutePath() }); } else { try { Files.copy(backupFile.toPath(), IMPL_FILE.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException exception) { // We're going to wrap it so end users know what went wrong throw new IOException("Critical Error! Could not restore Helios implementation to original copy" + "Try relaunching the Bootstrapper. If that doesn't work open a GitHub issue with details", exception); } } System.exit(0); } else { throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); } }
From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java
public static void checkExistsCanRead(File element) throws IOException, NullPointerException { if (element == null) { throw new NullPointerException("element is null"); }/*w w w . ja v a2s . c om*/ if (element.exists() == false) { throw new FileNotFoundException("\"" + element.getPath() + "\" in filesytem"); } if (element.canRead() == false) { throw new IOException("Can't read element \"" + element.getPath() + "\""); } }