List of usage examples for java.io File toPath
public Path toPath()
From source file:org.jetbrains.webdemo.examples.ExamplesLoader.java
private static void loadDefaultFiles(String folderPath, String projectId, List<ProjectFile> files, boolean loadTestVersion) throws IOException { File solutionFile = new File(folderPath + File.separator + "Solution.kt"); File testFile = new File(folderPath + File.separator + "Test.kt"); File taskFile = new File(folderPath + File.separator + "Task.kt"); if (testFile.exists() && !isAlreadyLoaded(files, testFile.getName())) { String testText = new String(Files.readAllBytes(testFile.toPath())).replaceAll("\r\n", "\n"); files.add(0, new TestFile(testText, projectId + "/" + testFile.getName())); }/* www . j a v a 2 s .c o m*/ if (loadTestVersion) { if (solutionFile.exists() && !isAlreadyLoaded(files, solutionFile.getName())) { String solutionText = new String(Files.readAllBytes(solutionFile.toPath())).replaceAll("\r\n", "\n"); files.add(0, new SolutionFile(solutionText, projectId + "/" + solutionFile.getName())); } } else { if (taskFile.exists() && !isAlreadyLoaded(files, taskFile.getName())) { String solutionText = new String(Files.readAllBytes(solutionFile.toPath())).replaceAll("\r\n", "\n"); String taskText = new String(Files.readAllBytes(taskFile.toPath())).replaceAll("\r\n", "\n"); files.add(0, new TaskFile(taskText, solutionText, projectId + "/" + taskFile.getName())); } } }
From source file:com.github.fritaly.dualcommander.Utils.java
public static Scan scan(Collection<File> collection) { Validate.notNull(collection, "The given collection of files is null"); final Scan scan = new Scan(); for (File element : collection) { if (element.isFile()) { scan.visitFile(element);//from w w w . java 2 s .c o m } else { try { Files.walkFileTree(element.toPath(), scan); } catch (IOException e) { throw new RuntimeException("Error when walking directory '" + element + "'", e); } } } return scan; }
From source file:com.github.blindpirate.gogradle.util.IOUtils.java
public static void markAndDeleteUnmarked(File rootDir, Predicate<File> predicate) { MarkDirectoryVisitor markVisitor = new MarkDirectoryVisitor(rootDir, predicate); walkFileTreeSafely(rootDir.toPath(), markVisitor); DeleteUnmarkedDirectoryVisitor deleteVisitor = new DeleteUnmarkedDirectoryVisitor(markVisitor); walkFileTreeSafely(rootDir.toPath(), deleteVisitor); }
From source file:com.ikanow.aleph2.harvest.logstash.utils.LogstashUtils.java
/** * Reads the given output file and outputs it to the logger with the spec'd log level. * @param logger/*from w w w . j a va2 s. co m*/ * @param level * @param output_file * @throws IOException */ public static void sendOutputToLogger(final IBucketLogger logger, final Level level, final File output_file, final Optional<Long> max_lines) throws IOException { // _logger.error("Reading output file: " + output_file + " to send to logger at level: " + level); Files.lines(output_file.toPath()).limit(max_lines.orElse(10000L)).forEach(line -> { try { //convert line to valid json, then parse json, build BMB object from it final String fixed_line = line.replaceAll(logstash_colon_search, logstash_colon_replace) .replaceAll(logstash_arrow_search, logstash_arrow_replace) .replaceAll(logstash_newline_search, logstash_newline_replace); final String plugin_fixed = fixPlugin(fixed_line); final ObjectNode line_object = (ObjectNode) _mapper.readTree(plugin_fixed); //move specific fields we want into BMB final Date date = parseLogstashDate(line_object.remove("timestamp").asText()); final Level logstash_level = Level.valueOf(line_object.remove("level").asText()); final String message = line_object.remove("message").asText(); //move everything else into details map logger.inefficientLog(logstash_level, new BasicMessageBean(date, true, LogstashHarvestService.class.getSimpleName(), "test_output", null, message, StreamSupport .stream(Spliterators.spliteratorUnknownSize(line_object.fields(), Spliterator.ORDERED), true) .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().asText())))); } catch (Exception ex) { //fallback on conversion failure logger.inefficientLog(level, ErrorUtils .buildSuccessMessage(LogstashHarvestService.class.getSimpleName(), "test_output", line)); } }); //TODO should we delete log file after we've read it? }
From source file:muffinc.yafdivj.helper.FeretHandler.java
public static void moveToHumans() { File file = new File(NEW_FOLDER); for (File file1 : file.listFiles()) { if (file1.isDirectory()) { for (File file2 : file1.listFiles(((FileFilter) new RegexFileFilter("\\w{10}d.*")))) { try { String newFolder = "/Users/Meth/Documents/FROG/src/test/resources/Humans/" + "H_" + file2.getName().substring(1, 5) + "/"; File file3 = new File(newFolder); if (!file3.exists()) { file3.mkdirs();//from w w w . jav a 2s . co m } Files.copy(file2.toPath(), new File(newFolder + file2.getName()).toPath()); } catch (IOException e) { e.printStackTrace(); } } } } }
From source file:net.sf.jabref.importer.OpenDatabaseAction.java
/** * Opens a new database.//from ww w . j a va 2s. c o m */ public static ParserResult loadDatabase(File fileToOpen, Charset defaultEncoding) throws IOException { // Open and parse file ParserResult result = new BibtexImporter().importDatabase(fileToOpen.toPath(), defaultEncoding); if (SpecialFieldsUtils.keywordSyncEnabled()) { NamedCompound compound = new NamedCompound("SpecialFieldSync"); for (BibEntry entry : result.getDatabase().getEntries()) { SpecialFieldsUtils.syncSpecialFieldsFromKeywords(entry, compound); } LOGGER.debug("Synchronized special fields based on keywords"); } return result; }
From source file:cc.kave.commons.externalserializationtests.ExternalTestCaseProvider.java
private static List<TestCase[]> getTestCasesInCurrentFolder(File currentDirectory, String rootPrefix) throws ClassNotFoundException, IOException { List<TestCase[]> testCases = new LinkedList<TestCase[]>(); Class<?> serializedType = Object.class; String expectedCompact = null; String expectedFormatted = null; for (File file : currentDirectory.listFiles()) { if (file.getName().equals(settingsFile)) { String className;// w w w .jav a 2 s .c om className = TestSettingsReader.readSection(file, "Java").get(ExternalTestSetting.SerializedType); serializedType = Class.forName(className); } if (file.getName().equals(expectedCompactFile)) { expectedCompact = new String(Files.readAllBytes(file.toPath())); } if (file.getName().equals(expectedFormattedFile)) { expectedFormatted = new String(Files.readAllBytes(file.toPath())); } } if (expectedCompact == null) { return new LinkedList<TestCase[]>(); } for (File file : currentDirectory.listFiles()) { boolean isInputFile = !file.getName().equals(settingsFile) && !file.getName().equals(expectedCompactFile) && !file.getName().equals(expectedFormattedFile); if (!isInputFile) { continue; } String input = new String(Files.readAllBytes(file.toPath())); testCases.add(new TestCase[] { new TestCase(getTestCaseName(file.getAbsolutePath(), rootPrefix), serializedType, input, expectedCompact, expectedFormatted) }); } return testCases; }
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 {/* w w w.j a v a 2s . co 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:com.jeet.cli.Admin.java
private static void downloadFile(Map fileMap) { System.out.print("Enter File Index(0 to cancel): "); String choise = null;/*w w w. j ava 2 s. c o m*/ try { choise = bufferRead.readLine(); } catch (IOException ioe) { System.err.println("Error in reading option."); System.err.println("Please try again."); downloadFile(fileMap); } if (choise != null && NumberUtils.isDigits(choise)) { Integer choiseInt = Integer.parseInt(choise); if (fileMap.containsKey(choiseInt)) { try { String key = fileMap.get(choiseInt).toString(); File file = FileUtil.downloadAndDecryptFile(key); String downloadFilePath = Constants.DOWNLOAD_FOLDER + fileMap.get(choiseInt).toString(); downloadFilePath = downloadFilePath.replaceAll("/", "\\\\"); Files.copy(file.toPath(), (new File(downloadFilePath)).toPath(), StandardCopyOption.REPLACE_EXISTING); System.out.println("File Downloaded to: " + downloadFilePath); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Error in downlaoding file."); } askFileListInputs(fileMap); } else if (choiseInt.equals(0)) { System.out.println("Download file canceled."); askFileListInputs(fileMap); } else { System.err.println("Please select from provided options only."); downloadFile(fileMap); } } else { System.err.println("Please enter digits only."); downloadFile(fileMap); } }
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() }); }/*from w w w . ja va 2 s. com*/ } } return params; }