Java Code Examples for java.nio.file.Files#isReadable()
The following examples show how to use
java.nio.file.Files#isReadable() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MD5Digester.java From p4ic4idea with Apache License 2.0 | 6 votes |
/** * Return the results of digesting an arbitrary file with this digester and * a specific client line ending. * <p> * Returns null if it can't read or digest the file for whatever reason; * otherwise the finalized digest is returned as a 32 byte hex string. * * @return - computed digest or null if computation failed */ @Nullable public String digestFileAs32ByteHex(@Nonnull File file, @Nullable Charset charset, boolean isRequireLineEndingConvert, @Nullable ClientLineEnding clientLineEnding) { requireNonNull(file, "Null file passed to MD5Digester.digestFileAs32ByteHex()"); if (Files.isReadable(file.toPath())) { try (FileInputStream inStream = new FileInputStream(file)) { reset(); if (nonNull(charset)) { digestEncodedStreamToUtf8(inStream, charset, isRequireLineEndingConvert, clientLineEnding); } else { digestStream(inStream, isRequireLineEndingConvert, clientLineEnding); } return digestAs32ByteHex(); } catch (IOException ioexc) { Log.error("error digesting file: " + file.getPath() + "; exception follows..."); Log.exception(ioexc); } } return null; }
Example 2
Source File: Preferences.java From gcs with Mozilla Public License 2.0 | 6 votes |
public void addRecentFile(Path path) { String extension = PathUtils.getExtension(path); if (Platform.isMacintosh() || Platform.isWindows()) { extension = extension.toLowerCase(); } for (FileType fileType : FileType.OPENABLE) { if (fileType.matchExtension(extension)) { if (Files.isReadable(path)) { mLastRecentFilesUpdateCounter++; path = path.normalize().toAbsolutePath(); mRecentFiles.remove(path); mRecentFiles.add(0, path); if (mRecentFiles.size() > MAX_RECENT_FILES) { mRecentFiles.remove(MAX_RECENT_FILES); } } break; } } }
Example 3
Source File: AbstractUnitTest.java From elasticsearch-shield-kerberos-realm with Apache License 2.0 | 6 votes |
private Path getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) { Path path = null; final URL fileUrl = PropertyUtil.class.getClassLoader().getResource(fileNameFromClasspath); if (fileUrl != null) { try { path = Paths.get(fileUrl.toURI()); if (!Files.isReadable(path) && !Files.isDirectory(path)) { log.error("Cannot read from {}, file does not exist or is not readable", path.toString()); return null; } if (!path.isAbsolute()) { log.warn("{} is not absolute", path.toString()); } return path; } catch (final URISyntaxException e) { //ignore } } else { log.error("Failed to load " + fileNameFromClasspath); } return null; }
Example 4
Source File: FileUtils.java From update4j with Apache License 2.0 | 6 votes |
public static boolean isZipFile(Path path) throws IOException { if (Files.isDirectory(path)) { return false; } if (!Files.isReadable(path)) { throw new IOException("Cannot read file " + path.toAbsolutePath()); } if (Files.size(path) < 4) { return false; } try (DataInputStream in = new DataInputStream(Files.newInputStream(path))) { int test = in.readInt(); return test == 0x504b0304; } }
Example 5
Source File: CompressedDirectory.java From docker-client with Apache License 2.0 | 6 votes |
static ImmutableList<DockerIgnorePathMatcher> parseDockerIgnore(Path dockerIgnorePath) throws IOException { final ImmutableList.Builder<DockerIgnorePathMatcher> matchersBuilder = ImmutableList.builder(); if (Files.isReadable(dockerIgnorePath) && Files.isRegularFile(dockerIgnorePath)) { for (final String line : Files.readAllLines(dockerIgnorePath, StandardCharsets.UTF_8)) { final String pattern = createPattern(line); if (isNullOrEmpty(pattern)) { log.debug("Will skip '{}' - because it's empty after trimming or it's a comment", line); continue; } if (pattern.startsWith("!")) { matchersBuilder .add(new DockerIgnorePathMatcher(dockerIgnorePath.getFileSystem(), pattern, false)); } else { matchersBuilder .add(new DockerIgnorePathMatcher(dockerIgnorePath.getFileSystem(), pattern, true)); } } } return matchersBuilder.build(); }
Example 6
Source File: FileUtil.java From JavaWeb with Apache License 2.0 | 5 votes |
public static Object readSerialize(String filePath) throws Exception{ Path p = Paths.get(filePath); if(Files.isReadable(p)){ BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(p)); ObjectInputStream ois = new ObjectInputStream(bis); Object obj = ois.readObject(); ois.close(); bis.close(); return obj; } return null; }
Example 7
Source File: HadoopClasspathUtils.java From ignite with Apache License 2.0 | 5 votes |
/** * Answers if the given path denotes existing directory. * * @param path The directory path. * @return {@code True} if the given path denotes an existing directory. */ public static boolean exists(String path) { if (F.isEmpty(path)) return false; Path p = Paths.get(path); return Files.exists(p) && Files.isDirectory(p) && Files.isReadable(p); }
Example 8
Source File: FileUtils.java From TerasologyLauncher with Apache License 2.0 | 5 votes |
/** * Checks if the given path exists, is a directory and can be read and written by the program. * * @param directory absolute path to the directory * * @throws IOException Reading the path fails in some way */ public static void ensureWritableDir(Path directory) throws IOException { if (!Files.exists(directory)) { Files.createDirectories(directory); } if (!Files.isDirectory(directory)) { throw new IOException("Not a directory: " + directory); } if (!Files.isReadable(directory) || !Files.isWritable(directory)) { throw new IOException("Missing read or write permissions: " + directory); } }
Example 9
Source File: JournalStore.java From baratine with GNU General Public License v2.0 | 5 votes |
JournalStore(Builder builder) throws IOException { _path = builder.getPath(); StoreBuilder storeBuilder = new StoreBuilder(_path); storeBuilder.mmap(builder.isMmap()); storeBuilder.services(builder.services()); _store = storeBuilder.build(); long segmentSize = builder.getSegmentSize(); segmentSize += (BLOCK_SIZE - 1); segmentSize -= segmentSize % BLOCK_SIZE; if (segmentSize > Integer.MAX_VALUE / 2) { throw new IllegalArgumentException(); } _segmentSize = (int) segmentSize; _blocksPerSegment = (int) (segmentSize / BLOCK_SIZE); _tailAddress = _segmentSize - BLOCK_SIZE; if (Files.isReadable(_path)) { _store.init(); initImpl(); } else { _store.create(); createImpl(); } }
Example 10
Source File: CompactionTest.java From pulsar with Apache License 2.0 | 5 votes |
@Override public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) { String CERT_FILE_PATH = "./src/test/resources/certificate/private-key." + keyName; if (Files.isReadable(Paths.get(CERT_FILE_PATH))) { try { keyInfo.setKey(Files.readAllBytes(Paths.get(CERT_FILE_PATH))); return keyInfo; } catch (IOException e) { Assert.fail("Failed to read certificate from " + CERT_FILE_PATH); } } else { Assert.fail("Certificate file " + CERT_FILE_PATH + " is not present or not readable."); } return null; }
Example 11
Source File: MtasFetchData.java From mtas with Apache License 2.0 | 5 votes |
/** * Gets the file. * * @param prefix the prefix * @param postfix the postfix * @return the file * @throws MtasParserException the mtas parser exception */ public Reader getFile(String prefix, String postfix) throws MtasParserException { String file = getString(); if ((file != null) && !file.equals("")) { if (prefix != null) { file = prefix + file; } if (postfix != null) { file = file + postfix; } Path path = (new File(file)).toPath(); if(Files.isReadable(path)) { try { return new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), StandardCharsets.UTF_8); } catch (IOException e1) { log.debug(e1); try { String text = new String(Files.readAllBytes(Paths.get(file)), StandardCharsets.UTF_8); return new StringReader(text); } catch (IOException e2) { log.debug(e2); throw new MtasParserException(e2.getMessage()); } } } else { throw new MtasParserException("file '"+file+"' does not exists or not readable"); } } else { throw new MtasParserException("no valid file: " + file); } }
Example 12
Source File: ArgumentProcessor.java From tailstreamer with MIT License | 5 votes |
/** * Validates the values of the command line arguments. * Before calling this method, {@link #parseArguments(String...)} must be called with the command-line arguments. * @return true if the argument values are valid and execution should continue, false if not. * @throws IllegalStateException if no arguments were previously parsed. */ public boolean validateArguments() { if (options == null) { throw new IllegalStateException("No arguments have been parsed"); } List<?> nonOptionArgs = options.nonOptionArguments(); if (options.has("h") || options.has("v")) { return true; } else if (options.has("encryptPassword")) { if (nonOptionArgs.isEmpty()) { validationErrorMessage = "No password specified"; return false; } } else if (nonOptionArgs.isEmpty()) { validationErrorMessage = MESSAGE_NO_FILE_SPECIFIED; return false; } if (options.has("encryptPassword")) { return true; } else { String filePath = (String) nonOptionArgs.get(0); if (!new File(filePath).exists()) { validationErrorMessage = String.format(MESSAGE_FILE_NOT_FOUND, nonOptionArgs.get(0)); return false; } else if (!Files.isReadable(Paths.get(filePath))) { validationErrorMessage = String.format(MESSAGE_READ_PERMISSION, nonOptionArgs.get(0)); return false; } } return true; }
Example 13
Source File: Utils.java From lwjglbook with Apache License 2.0 | 5 votes |
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException { ByteBuffer buffer; Path path = Paths.get(resource); if (Files.isReadable(path)) { try (SeekableByteChannel fc = Files.newByteChannel(path)) { buffer = BufferUtils.createByteBuffer((int) fc.size() + 1); while (fc.read(buffer) != -1) ; } } else { try ( InputStream source = Utils.class.getResourceAsStream(resource); ReadableByteChannel rbc = Channels.newChannel(source)) { buffer = createByteBuffer(bufferSize); while (true) { int bytes = rbc.read(buffer); if (bytes == -1) { break; } if (buffer.remaining() == 0) { buffer = resizeBuffer(buffer, buffer.capacity() * 2); } } } } buffer.flip(); return buffer; }
Example 14
Source File: PathDocFileFactory.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
/** Return true if the file can be read. */ public boolean canRead() { return Files.isReadable(file); }
Example 15
Source File: IndexFiles.java From lucene-solr with Apache License 2.0 | 4 votes |
/** Index all text files under a directory. */ public static void main(String[] args) { String usage = "java org.apache.lucene.demo.IndexFiles" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with SearchFiles"; String indexPath = "index"; String docsPath = null; boolean create = true; for(int i=0;i<args.length;i++) { if ("-index".equals(args[i])) { indexPath = args[i+1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i+1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.err.println("Usage: " + usage); System.exit(1); } final Path docDir = Paths.get(docsPath); if (!Files.isReadable(docDir)) { System.out.println("Document directory '" +docDir.toAbsolutePath()+ "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(Paths.get(indexPath)); Analyzer analyzer = new StandardAnalyzer(); IndexWriterConfig iwc = new IndexWriterConfig(analyzer); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // // iwc.setRAMBufferSizeMB(256.0); IndexWriter writer = new IndexWriter(dir, iwc); indexDocs(writer, docDir); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
Example 16
Source File: FileSourceConfig.java From pulsar with Apache License 2.0 | 4 votes |
public void validate() { if (StringUtils.isBlank(inputDirectory)) { throw new IllegalArgumentException("Required property not set."); } else if (Files.notExists(Paths.get(inputDirectory), LinkOption.NOFOLLOW_LINKS)) { throw new IllegalArgumentException("Specified input directory does not exist"); } else if (!Files.isReadable(Paths.get(inputDirectory))) { throw new IllegalArgumentException("Specified input directory is not readable"); } else if (Optional.ofNullable(keepFile).orElse(false) && !Files.isWritable(Paths.get(inputDirectory))) { throw new IllegalArgumentException("You have requested the consumed files to be deleted, but the " + "source directory is not writeable."); } if (StringUtils.isNotBlank(fileFilter)) { try { Pattern.compile(fileFilter); } catch (final PatternSyntaxException psEx) { throw new IllegalArgumentException("Invalid Regex pattern provided for fileFilter"); } } if (minimumFileAge != null && Math.signum(minimumFileAge) < 0) { throw new IllegalArgumentException("The property minimumFileAge must be non-negative"); } if (maximumFileAge != null && Math.signum(maximumFileAge) < 0) { throw new IllegalArgumentException("The property maximumFileAge must be non-negative"); } if (minimumSize != null && Math.signum(minimumSize) < 0) { throw new IllegalArgumentException("The property minimumSize must be non-negative"); } if (maximumSize != null && Math.signum(maximumSize) < 0) { throw new IllegalArgumentException("The property maximumSize must be non-negative"); } if (pollingInterval != null && pollingInterval <= 0) { throw new IllegalArgumentException("The property pollingInterval must be greater than zero"); } if (numWorkers != null && numWorkers <= 0) { throw new IllegalArgumentException("The property numWorkers must be greater than zero"); } }
Example 17
Source File: PathDocFileFactory.java From hottub with GNU General Public License v2.0 | 4 votes |
/** Return true if the file can be read. */ public boolean canRead() { return Files.isReadable(file); }
Example 18
Source File: TestUtils.java From CogniCrypt with Eclipse Public License 2.0 | 3 votes |
/** * This method passed a Java file into a byte array * * @param project * @param packageName * @param unit * @return * @throws IOException * @throws CoreException */ public static byte[] fileToByteArray(final DeveloperProject project, final String packageName, final ICompilationUnit cu) throws IOException, CoreException { final File f = new File(getFilePathInProject(project, packageName, cu)); if (!(f.exists() && Files.isReadable(f.toPath()))) { throw new IOException(); } return Files.readAllBytes(Paths.get(f.getPath())); }
Example 19
Source File: PathResource.java From lams with GNU General Public License v2.0 | 2 votes |
/** * This implementation checks whether the underlying file is marked as readable * (and corresponds to an actual file with content, not to a directory). * @see java.nio.file.Files#isReadable(Path) * @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...) */ @Override public boolean isReadable() { return (Files.isReadable(this.path) && !Files.isDirectory(this.path)); }
Example 20
Source File: XsvLocatableTableCodec.java From gatk with BSD 3-Clause "New" or "Revised" License | 2 votes |
/** * Asserts that the given {@code filePath} is a valid file from which to read. * @param filePath The {@link Path} to the data file to validate. * @return {@code true} if the given {@code filePath} is valid; {@code false} otherwise. */ private boolean validateInputFileCanBeRead(final Path filePath) { return Files.exists(filePath) && Files.isReadable(filePath) && !Files.isDirectory(filePath); }