List of usage examples for java.nio.file Path getFileName
Path getFileName();
From source file:io.anserini.index.IndexWebCollection.java
static Deque<Path> discoverWarcFiles(Path p, final String suffix) { final Deque<Path> stack = new ArrayDeque<>(); FileVisitor<Path> fv = new SimpleFileVisitor<Path>() { @Override/*from w ww . j a va 2s.c o m*/ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path name = file.getFileName(); if (name != null && name.toString().endsWith(suffix)) stack.add(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { if ("OtherData".equals(dir.getFileName().toString())) { LOG.info("Skipping: " + dir); return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException ioe) { LOG.error("Visiting failed for " + file.toString(), ioe); return FileVisitResult.SKIP_SUBTREE; } }; try { Files.walkFileTree(p, fv); } catch (IOException e) { LOG.error("IOException during file visiting", e); } return stack; }
From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java
/** * Gets xdocs documentation file paths.//from w ww .j a v a 2 s . co m * @param xdocsDirectoryPath xdocs directory path. * @return a list of xdocs file paths. * @throws IOException if an I/O error occurs. */ private static Set<Path> getXdocsFilePaths(String xdocsDirectoryPath) throws IOException { final Path directory = Paths.get(xdocsDirectoryPath); final Set<Path> xdocs = new HashSet<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, "*.xml")) { for (Path entry : stream) { final String fileName = entry.getFileName().toString(); if (fileName.startsWith("config_")) { xdocs.add(entry); } } return xdocs; } }
From source file:com.willwinder.universalgcodesender.utils.FirmwareUtils.java
/** * Copy any missing files from the the jar's resources/firmware_config/ dir * into the settings/firmware_config dir. *//* w w w . j a v a 2 s . co m*/ public synchronized static void initialize() { System.out.println("Initializing firmware... ..."); File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME); // Create directory if it's missing. if (!firmwareConfig.exists()) { firmwareConfig.mkdirs(); } FileSystem fileSystem = null; // Copy firmware config files. try { final String dir = "/resources/firmware_config/"; URI location = FirmwareUtils.class.getResource(dir).toURI(); Path myPath; if (location.getScheme().equals("jar")) { try { // In case the filesystem already exists. fileSystem = FileSystems.getFileSystem(location); } catch (FileSystemNotFoundException e) { // Otherwise create the new filesystem. fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap()); } myPath = fileSystem.getPath(dir); } else { myPath = Paths.get(location); } Stream<Path> files = Files.walk(myPath, 1); for (Path path : (Iterable<Path>) () -> files.iterator()) { System.out.println(path); final String name = path.getFileName().toString(); File fwConfig = new File(firmwareConfig, name); if (name.endsWith(".json")) { boolean copyFile = !fwConfig.exists(); ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path)); // If the file is outdated... ask the user (once). if (fwConfig.exists()) { ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig)); boolean outOfDate = current.getVersion() < jarSetting.getVersion(); if (outOfDate && !userNotified && !overwriteOldFiles) { int result = NarrowOptionPane.showNarrowConfirmDialog(200, Localization.getString("settings.file.outOfDate.message"), Localization.getString("settings.file.outOfDate.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); overwriteOldFiles = result == JOptionPane.OK_OPTION; userNotified = true; } if (overwriteOldFiles) { copyFile = true; jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom; } } // Copy file from jar to firmware_config directory. if (copyFile) { try { save(fwConfig, jarSetting); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } } } catch (Exception ex) { String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"), ex.getLocalizedMessage()); GUIHelpers.displayErrorDialog(errorMessage); logger.log(Level.SEVERE, errorMessage, ex); } finally { if (fileSystem != null) { try { fileSystem.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Problem closing filesystem.", ex); } } } configFiles.clear(); for (File f : firmwareConfig.listFiles()) { try { ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class); //ConfigLoader config = new ConfigLoader(f); configFiles.put(config.getName(), new ConfigTuple(config, f)); } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) { GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath()); } } }
From source file:com.fizzed.stork.deploy.Archive.java
static public Archive pack(Path unpackedDir, Path archiveFile, String format) throws IOException { log.info("Packing {} to {}", unpackedDir, archiveFile); try (ArchiveOutputStream aos = newArchiveOutputStream(archiveFile, format)) { packEntry(aos, unpackedDir, unpackedDir.getFileName().toString(), false); }//from w w w. j a v a2 s .c o m return new Archive(archiveFile); }
From source file:org.bonitasoft.web.designer.controller.utils.HttpFile.java
/** * Write headers and content in the response *//*from w ww. j a v a2 s . com*/ private static void writeFileInResponse(HttpServletResponse response, Path filePath, String mimeType, String contentDispositionType) throws IOException { response.setHeader("Content-Type", mimeType); response.setHeader("Content-Length", String.valueOf(filePath.toFile().length())); response.setHeader("Content-Disposition", new StringBuilder().append(contentDispositionType) .append("; filename=\"").append(filePath.getFileName()).append("\"").toString()); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); try (OutputStream out = response.getOutputStream()) { Files.copy(filePath, out); } }
From source file:com.massabot.codesender.utils.FirmwareUtils.java
public synchronized static void initialize() { System.out.println("Initializing firmware... ..."); File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME); // Create directory if it's missing. if (!firmwareConfig.exists()) { firmwareConfig.mkdirs();/* www. j a va 2 s . co m*/ } FileSystem fileSystem = null; // Copy firmware config files. try { final String dir = "/resources/firmware_config/"; URI location = FirmwareUtils.class.getResource(dir).toURI(); Path myPath; if (location.getScheme().equals("jar")) { try { // In case the filesystem already exists. fileSystem = FileSystems.getFileSystem(location); } catch (FileSystemNotFoundException e) { // Otherwise create the new filesystem. fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap()); } myPath = fileSystem.getPath(dir); } else { myPath = Paths.get(location); } Stream<Path> files = Files.walk(myPath, 1); for (Path path : (Iterable<Path>) () -> files.iterator()) { System.out.println(path); final String name = path.getFileName().toString(); File fwConfig = new File(firmwareConfig, name); if (name.endsWith(".json")) { boolean copyFile = !fwConfig.exists(); ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path)); // If the file is outdated... ask the user (once). if (fwConfig.exists()) { ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig)); boolean outOfDate = current.getVersion() < jarSetting.getVersion(); if (outOfDate && !userNotified && !overwriteOldFiles) { int result = NarrowOptionPane.showNarrowConfirmDialog(200, Localization.getString("settings.file.outOfDate.message"), Localization.getString("settings.file.outOfDate.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); overwriteOldFiles = result == JOptionPane.OK_OPTION; userNotified = true; } if (overwriteOldFiles) { copyFile = true; jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom; } } // Copy file from jar to firmware_config directory. if (copyFile) { try { save(fwConfig, jarSetting); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } } } catch (Exception ex) { String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"), ex.getLocalizedMessage()); GUIHelpers.displayErrorDialog(errorMessage); logger.log(Level.SEVERE, errorMessage, ex); } finally { if (fileSystem != null) { try { fileSystem.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Problem closing filesystem.", ex); } } } configFiles.clear(); for (File f : firmwareConfig.listFiles()) { try { ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class); // ConfigLoader config = new ConfigLoader(f); configFiles.put(config.getName(), new ConfigTuple(config, f)); } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) { GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath()); } } }
From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java
/** * Create a jar file from the given directory. * @param dir source directory/* w w w .j a va 2 s .c o m*/ * @param jarFile jar file name * @throws IOException when file cannot be created */ public static void createJar(File dir, File jarFile) throws IOException { final Map<String, ?> env = Collections.singletonMap("create", "true"); if (jarFile.exists() && !jarFile.delete()) { throw new RuntimeException("Failed to remove " + jarFile); } URI uri = URI.create("jar:" + jarFile.toURI()); try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { File manifestFile = new File(dir, JarFile.MANIFEST_NAME); Files.createDirectory(zipfs.getPath("META-INF")); try (final OutputStream out = Files.newOutputStream(zipfs.getPath(JarFile.MANIFEST_NAME))) { if (!manifestFile.exists()) { new Manifest().write(out); } else { FileUtils.copyFile(manifestFile, out); } } final java.nio.file.Path root = dir.toPath(); Files.walkFileTree(root, new java.nio.file.SimpleFileVisitor<Path>() { String relativePath; @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { relativePath = root.relativize(dir).toString(); if (!relativePath.isEmpty()) { if (!relativePath.endsWith("/")) { relativePath += "/"; } if (!relativePath.equals("META-INF/")) { final Path dstDir = zipfs.getPath(relativePath); Files.createDirectory(dstDir); } } return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String name = relativePath + file.getFileName(); if (!JarFile.MANIFEST_NAME.equals(name)) { try (final OutputStream out = Files.newOutputStream(zipfs.getPath(name))) { FileUtils.copyFile(file.toFile(), out); } } return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { relativePath = root.relativize(dir.getParent()).toString(); if (!relativePath.isEmpty() && !relativePath.endsWith("/")) { relativePath += "/"; } return super.postVisitDirectory(dir, exc); } }); } }
From source file:com.example.bot.spring.KitchenSinkController.java
private static DownloadedContent createTempFile(String ext) { String fileName = LocalDateTime.now().toString() + '-' + UUID.randomUUID().toString() + '.' + ext; Path tempFile = KitchenSinkApplication.downloadedContentDir.resolve(fileName); tempFile.toFile().deleteOnExit();//from w ww. j a va 2 s . c om return new DownloadedContent(tempFile, createUri("/downloaded/" + tempFile.getFileName())); }
From source file:com.fizzed.stork.deploy.Archive.java
static public void packEntry(ArchiveOutputStream aos, Path dirOrFile, String base, boolean appendName) throws IOException { String entryName = base;//from ww w . jav a 2 s .c o m if (appendName) { if (!entryName.equals("")) { if (!entryName.endsWith("/")) { entryName += "/" + dirOrFile.getFileName(); } else { entryName += dirOrFile.getFileName(); } } else { entryName += dirOrFile.getFileName(); } } ArchiveEntry entry = aos.createArchiveEntry(dirOrFile.toFile(), entryName); if (Files.isRegularFile(dirOrFile)) { if (entry instanceof TarArchiveEntry && Files.isExecutable(dirOrFile)) { // -rwxr-xr-x ((TarArchiveEntry) entry).setMode(493); } else { // keep default mode } } aos.putArchiveEntry(entry); if (Files.isRegularFile(dirOrFile)) { Files.copy(dirOrFile, aos); aos.closeArchiveEntry(); } else { aos.closeArchiveEntry(); List<Path> children = Files.list(dirOrFile).collect(Collectors.toList()); if (children != null) { for (Path childFile : children) { packEntry(aos, childFile, entryName + "/", true); } } } }
From source file:com.basistech.rosette.api.RosetteAPITest.java
@Parameterized.Parameters public static Collection<Object[]> data() throws URISyntaxException, IOException { File dir = new File("src/test/mock-data/response"); Collection<Object[]> params = new ArrayList<>(); try (DirectoryStream<Path> paths = Files.newDirectoryStream(dir.toPath())) { for (Path file : paths) { if (file.toString().endsWith(".json")) { params.add(new Object[] { file.getFileName().toString() }); }// ww w . ja v a2 s .com } } return params; }