For IntelliJ IDEA,
Android Studio or Eclipse



private void myMethod () {Path p =
String first;Paths.get(first)
File file;file.toPath()
Files.createTempFile("<changeme>", "<changeme>")
- Smart code suggestions by Codota
}
public void testCreateParentDirectories_nonDirectoryParentExists() throws IOException { Path parent = createTempFile(); assertTrue(Files.isRegularFile(parent)); Path file = parent.resolve("foo"); try { MoreFiles.createParentDirectories(file); fail(); } catch (IOException expected) { } }
private void disableLogFileAccess() throws IOException { logFile.createNewFile(); logFile.deleteOnExit(); Path path = Paths.get(logFile.toURI()); Set<PosixFilePermission> permissions = Collections.emptySet(); try { Files.setPosixFilePermissions(path, permissions); } catch (UnsupportedOperationException e) { path.toFile().setReadOnly(); } }
public void testCreateParentDirectories_multipleParentsNeeded() throws IOException { Path path = tempDir.resolve("grandparent/parent/nonexistent.file"); Path parent = path.getParent(); Path grandparent = parent.getParent(); assertFalse(Files.exists(grandparent)); assertFalse(Files.exists(parent)); MoreFiles.createParentDirectories(path); assertTrue(Files.exists(parent)); assertTrue(Files.exists(grandparent)); }
public void testDeleteRecursively_nonDirectoryFile() throws IOException { try (FileSystem fs = newTestFileSystem(SECURE_DIRECTORY_STREAM)) { Path file = fs.getPath("dir/a"); assertTrue(Files.isRegularFile(file, NOFOLLOW_LINKS)); MoreFiles.deleteRecursively(file); assertFalse(Files.exists(file, NOFOLLOW_LINKS)); Path symlink = fs.getPath("/symlinktodir"); assertTrue(Files.isSymbolicLink(symlink)); Path realSymlinkTarget = symlink.toRealPath(); assertTrue(Files.isDirectory(realSymlinkTarget, NOFOLLOW_LINKS)); MoreFiles.deleteRecursively(symlink); assertFalse(Files.exists(symlink, NOFOLLOW_LINKS)); assertTrue(Files.isDirectory(realSymlinkTarget, NOFOLLOW_LINKS)); } }
import java.nio.file.Path; import java.nio.file.Paths; public class Test { public static void main(String[] args) { Path pathAbsolute = Paths.get("/var/data/stuff/xyz.dat"); Path pathBase = Paths.get("/var/data"); Path pathRelative = pathBase.relativize(pathAbsolute); System.out.println(pathRelative); } }
public void testCreateParentDirectories_symlinkParentExists() throws IOException { Path symlink = tempDir.resolve("linkToDir"); Files.createSymbolicLink(symlink, root()); Path file = symlink.resolve("foo"); MoreFiles.createParentDirectories(file); }
private static List<URI> retainValid(List<URI> inputs, boolean recursive) { List<URI> retained = new ArrayList<>(); for (URI input : inputs) { boolean retain; if (isFileOrDir(input)) { Path inputPath = Paths.get(input); retain = !inputPath.getFileName().toString().startsWith(".") && (recursive || !Files.isDirectory(inputPath)); } else { retain = true; } if (retain) { retained.add(input); } } return retained; }
public static final void externalConfiguredTo(String folder) { String unixLikeFolder = Paths.get(folder).toAbsolutePath().toString().replace("\\", "/"); LOG.warn("Registering external static files folder [{}] as [{}].", folder, unixLikeFolder); external = removeLeadingAndTrailingSlashesFrom(unixLikeFolder); }
private FileLock createLockedStoreLockFileIn( Path parent ) throws IOException { Path storeLockFile = Files.createFile( Paths.get( parent.toString(), STORE_LOCK_FILENAME ) ); channel = FileChannel.open( storeLockFile, READ, WRITE ); return channel.lock( 0, Long.MAX_VALUE, true ); }
private Map<Path, Description> describeRecursively( Path directory ) throws IOException { return Files.walk( directory ) .map( path -> pair( directory.relativize( path ), describe( path ) ) ) .collect( HashMap::new, ( pathDescriptionHashMap, pathDescriptionPair ) -> pathDescriptionHashMap.put( pathDescriptionPair.first(), pathDescriptionPair.other() ), HashMap::putAll ); }
private void assemble0(Path in, Path output) throws IOException, URISyntaxException { if (Files.isDirectory(in)) { // a dir travelFileTree(in, output); } else if (in.toString().endsWith(".j")) { assemble1(in, output); } else { try (FileSystem fs = openZip(in)) { travelFileTree(fs.getPath("/"), output); } } }
@Test public void shouldMakeFromCanonical() throws IOException, CommandFailed, IncorrectUsage, IncorrectFormat { Path dataDir = testDirectory.directory( "some-other-path" ).toPath(); Path databaseDir = dataDir.resolve( "databases/foo.db" ); Files.createDirectories( databaseDir ); Files.write( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ), asList( formatProperty( data_directory, dataDir ) ) ); new LoadCommand( homeDir, configDir, loader ) .execute( ArrayUtil.concat( new String[]{"--database=foo.db", "--from=foo.dump"} ) ); verify( loader ).load( eq( Paths.get( new File( "foo.dump" ).getCanonicalPath() ) ), any(), any() ); }
private static URI createTmpCsvFile() { try { Path csvFile = Files.createTempFile( "test", ".csv" ); List<String> lines = range( 0, 50000 ).mapToObj( i -> "Foo-" + i + ", Bar-" + i ).collect( toList() ); return Files.write( csvFile, lines ).toAbsolutePath().toUri(); } catch ( IOException e ) { throw new UncheckedIOException( e ); } }
private static Path buildOutputPath(URI input, String suffix) throws IOException { Path outDir; String inputFileName; if ("file".equals(input.getScheme())) { Path inputPath = Paths.get(input); outDir = inputPath.getParent(); inputFileName = inputPath.getFileName().toString(); } else { outDir = Paths.get(".").toRealPath(); String[] pathElements = input.getPath().split("/"); inputFileName = pathElements[pathElements.length - 1]; } // Replace/add extension int pos = inputFileName.lastIndexOf('.'); if (pos > 0) { inputFileName = inputFileName.substring(0, pos) + suffix; } else { inputFileName += suffix; } return outDir.resolve(inputFileName); }
/** Loads a resource of the provided class into a {@link JavaFileObject}. */ public JavaFileObject forResource(Class<?> clazz, String fileName) { Path path = fileSystem.getPath("/", clazz.getPackage().getName().replace('.', '/'), fileName); try (InputStream is = findResource(clazz, fileName)) { Files.createDirectories(path.getParent()); Files.copy(is, path); } catch (IOException e) { throw new IOError(e); } return Iterables.getOnlyElement(getJavaFileObjects(path)); }
private String createClassOutsideClasspath(String className) throws Exception { File dir = Files.createTempDirectory("vertx").toFile(); dir.deleteOnExit(); File source = new File(dir, className + ".java"); Files.write(source.toPath(), ("public class " + className + " extends io.vertx.core.AbstractVerticle {} ").getBytes()); URLClassLoader loader = new URLClassLoader(new URL[]{dir.toURI().toURL()}, Thread.currentThread().getContextClassLoader()); CompilingClassLoader compilingClassLoader = new CompilingClassLoader(loader, className + ".java"); compilingClassLoader.loadClass(className); byte[] bytes = compilingClassLoader.getClassBytes(className); assertNotNull(bytes); File classFile = new File(dir, className + ".class"); Files.write(classFile.toPath(), bytes); return dir.getAbsolutePath(); }
private Path getOrCreateMetaInf() throws URISyntaxException, IOException { Path root = Paths.get(Thread.currentThread().getContextClassLoader().getResource(".").toURI()); Path metaInf = root.resolve("META-INF"); if (!Files.exists(metaInf)) { Files.createDirectory(metaInf); } return metaInf; } }
static void createJar(final URI jarURI, final File workDir, final File f) throws Exception { final Map<String, String> env = new HashMap<>(); env.put("create", "true"); final URI uri = URI.create("jar:file://" + jarURI.getRawPath()); try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { final Path path = zipfs.getPath(workDir.toPath().relativize(f.toPath()).toString()); if (path.getParent() != null) { Files.createDirectories(path.getParent()); } Files.copy(f.toPath(), path, StandardCopyOption.REPLACE_EXISTING ); } }