Java 类java.nio.file.Files 实例源码

项目:openapi-annotation-processor    文件:PathUtils.java   
/**
 * @param path The patch to scan
 * @return All direct and indirect sub files
 */
public static List<Path> subFiles(Path path) {
    List<Path> files = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
        for (Path subPath : directoryStream) {
            if (Files.isDirectory(subPath)) {
                files.addAll(subFiles(subPath));
            } else {
                files.add(subPath);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return files;
}
项目:OpenJSharp    文件:Main.java   
/**
 * Outputs the class index table to the INDEX.LIST file of the
 * root jar file.
 */
void dumpIndex(String rootjar, JarIndex index) throws IOException {
    File jarFile = new File(rootjar);
    Path jarPath = jarFile.toPath();
    Path tmpPath = createTempFileInSameDirectoryAs(jarFile).toPath();
    try {
        if (update(Files.newInputStream(jarPath),
                   Files.newOutputStream(tmpPath),
                   null, index)) {
            try {
                Files.move(tmpPath, jarPath, REPLACE_EXISTING);
            } catch (IOException e) {
                throw new IOException(getMsg("error.write.file"), e);
            }
        }
    } finally {
        Files.deleteIfExists(tmpPath);
    }
}
项目:smart-testing    文件:CustomProviderInfo.java   
void retrieveCustomProviderInformation(File projectDir, String failsafePluginVersion) {

        final boolean isFailsafePlugin = failsafePluginVersion != null;
        final String prefix = isFailsafePlugin ? LoaderVersionExtractor.ARTIFACT_ID_MAVEN_FAILSAFE_PLUGIN
            : LoaderVersionExtractor.ARTIFACT_ID_MAVEN_SUREFIRE_PLUGIN;

        File dir = TemporaryInternalFiles.createCustomProvidersDirAction(projectDir, prefix).getFile();

        if (dir.exists() && dir.listFiles().length > 0) {
            File customProviderInfoFile = dir.listFiles()[0];
            gav = customProviderInfoFile.getName();
            try {
                providerClassName = new String(Files.readAllBytes(customProviderInfoFile.toPath()));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    }
项目:rdf4j-schema-generator    文件:SchemaGeneratorTest.java   
/**
 * Test method for {@link com.github.ansell.rdf4j.schemagenerator.RDF4JSchemaGeneratorCore#generate(java.nio.file.Path)}.
 */
@Test
public final void testUpperUnderscoreCaseString() throws Exception {
    Path outputPath = testDir.resolve("output");
    Files.createDirectories(outputPath);

    RDF4JSchemaGeneratorCore testBuilder = new RDF4JSchemaGeneratorCore(inputPath.toAbsolutePath().toString(), format);

    testBuilder.setStringConstantCase(CaseFormat.UPPER_UNDERSCORE);

    Path javaFilePath = outputPath.resolve("Test.java");
    testBuilder.generate(javaFilePath);
    assertTrue("Java file was not found", Files.exists(javaFilePath));
    assertTrue("Java file was empty", Files.size(javaFilePath) > 0);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Files.copy(javaFilePath, out);
    String result = new String(out.toByteArray(), StandardCharsets.UTF_8);
    assertTrue("Did not find expected key case", result.contains("PROPERTY_LOCALISED4 = "));
    assertTrue("Did not find original URI", result.contains("\"http://example.com/ns/ontology#propertyLocalised4\""));
}
项目:openjdk-jdk10    文件:ValidateModulesTest.java   
/**
 * Test two modules with the same name in different directories.
 */
public void testShadowed() throws Exception {
    Path tmpdir = Files.createTempDirectory("tmp");

    Path classes = Files.createDirectory(tmpdir.resolve("classes"));
    touch(classes, "org/foo/Bar.class");

    Path lib1 = Files.createDirectory(tmpdir.resolve("lib1"));
    JarUtils.createJarFile(lib1.resolve("foo-1.0.jar"), classes);

    Path lib2 = Files.createDirectory(tmpdir.resolve("lib2"));
    JarUtils.createJarFile(lib2.resolve("foo-2.0.jar"), classes);

    run("-p", lib1 + File.pathSeparator + lib2, "--validate-modules")
            .shouldContain("shadowed by")
            .shouldHaveExitValue(0);
}
项目:incubator-netbeans    文件:ModuleMainClassTest.java   
private String getMainClass(Path p) throws IOException {
    try(final InputStream in = Files.newInputStream(p)) {
        final ClassFile cf = new ClassFile(in);
        final ConstantPool cp = cf.getConstantPool();
        for (Attribute attr : cf.getAttributes()) {
            int nameIndex = attr.getNameIndex();
            ConstantPool.CPInfo entry = cp.get(nameIndex);
            if ("ModuleMainClass".equals(entry.getValue())) {   //NOI18N
                byte[] value = attr.getValue();
                nameIndex = (value[0] & 0xff) << 8 | (value[1] & 0xff);
                entry = cp.get(nameIndex);
                return ((String)entry.getValue()).replace('/', '.');    //NOI18N
            }
        }
    }
    return null;
}
项目:octane-cucumber-jvm    文件:OutputFile.java   
public File getOutputFile(Class testClass) {
    if(testClass == null) {
        throw new IllegalArgumentException("testClass cannot be null");
    }

    try {
        File outputFolder = new File(Constants.RESULTS_FOLDER);
        Files.createDirectories(outputFolder.toPath()); // if directory already exists will do nothing

        //testClass.getName() is the unique identifier of the class
        String fileName = String.format("%s_%s", testClass.getName(), Constants.RESULTS_FILE_NAME_POSTFIX);
        File outputFile = new File(outputFolder, fileName);
        outputFile.createNewFile(); // if file already exists will do nothing
        return outputFile;
    } catch (IOException e) {
        throw new CucumberException(Constants.errorPrefix + "Failed to create cucumber results output directory", e);
    }
}
项目:CloudNet    文件:PacketInInstallUpdate.java   
@Override
public void handleInput(Document data, PacketSender packetSender)
{
    try
    {
        URLConnection url = new java.net.URL(data.getString("url")).openConnection();
        url.connect();
        if(System.getProperty("os.name").toLowerCase().contains("windows"))
        {
            Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper-" + NetworkUtils.RANDOM.nextLong() + ".jar"));
        }
        else
        {
            Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper.jar"));
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
项目:openjdk-jdk10    文件:ModuleReaderTest.java   
/**
 * Test ModuleReader to JMOD
 */
public void testJMod() throws IOException {
    Path dir = Files.createTempDirectory(USER_DIR, "mlib");

    // jmod create --class-path mods/${TESTMODULE}  mlib/${TESTMODULE}.jmod
    String cp = MODS_DIR.resolve(TEST_MODULE).toString();
    String jmod = dir.resolve("m.jmod").toString();
    String[] args = { "create", "--class-path", cp, jmod };
    ToolProvider jmodTool = ToolProvider.findFirst("jmod")
        .orElseThrow(() ->
            new RuntimeException("jmod tool not found")
        );
    assertEquals(jmodTool.run(System.out, System.out, args), 0);

    test(dir);
}
项目:Avalon-Executive    文件:PreProcessor.java   
public File createFile(Submission submission) throws IOException {
    File workDirFile = new File(Constants._WORK_DIR());

    if (!workDirFile.exists() && !workDirFile.mkdirs())
        throw new IOException("failed to create directory: " + Constants._WORK_DIR());

    Language language = submission.getLanguage();
    String codeFilePath = String.format("%s/%s.%s", Constants._WORK_DIR(),
            submission.getSubmitTime(), getCodeFileSuffix(language.getCompileCmd()));

    String[] codeLinesArray = replaceClassName(language, submission.getDecodedCode())
            .replace("\r", "")
            .split("\n");

    Files.createDirectories(Paths.get(codeFilePath).getParent());

    BufferedWriter writer = new BufferedWriter(new FileWriter(codeFilePath));
    for (String thisLineCode : codeLinesArray) {
        writer.write(thisLineCode);
        writer.newLine();
    }
    IOUtils.closeQuietly(writer);
    return new File(codeFilePath);
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:ImageService.java   
/**
 * Pre-load some fake images
 *
 * @return Spring Boot {@link CommandLineRunner} automatically run after app context is loaded.
 */
@Bean
CommandLineRunner setUp() throws IOException {
    return (args) -> {
        FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT));

        Files.createDirectory(Paths.get(UPLOAD_ROOT));

        FileCopyUtils.copy("Test file",
            new FileWriter(UPLOAD_ROOT +
                "/learning-spring-boot-cover.jpg"));

        FileCopyUtils.copy("Test file2",
            new FileWriter(UPLOAD_ROOT +
                "/learning-spring-boot-2nd-edition-cover.jpg"));

        FileCopyUtils.copy("Test file3",
            new FileWriter(UPLOAD_ROOT + "/bazinga.png"));
    };
}
项目:elasticsearch_my    文件:TruncateTranslogIT.java   
private Set<Path> getTranslogDirs(String indexName) throws IOException {
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(new String[]{indexName}, false);
    final Index idx = state.metaData().index(indexName).getIndex();
    List<ShardIterator> iterators = iterableAsArrayList(shardIterators);
    ShardIterator shardIterator = RandomPicks.randomFrom(random(), iterators);
    ShardRouting shardRouting = shardIterator.nextOrNull();
    assertNotNull(shardRouting);
    assertTrue(shardRouting.primary());
    assertTrue(shardRouting.assignedToNode());
    String nodeId = shardRouting.currentNodeId();
    NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
    Set<Path> translogDirs = new TreeSet<>(); // treeset makes sure iteration order is deterministic
    for (FsInfo.Path fsPath : nodeStatses.getNodes().get(0).getFs()) {
        String path = fsPath.getPath();
        final String relativeDataLocationPath =  "indices/"+ idx.getUUID() +"/" + Integer.toString(shardRouting.getId()) + "/translog";
        Path translogPath = PathUtils.get(path).resolve(relativeDataLocationPath);
        if (Files.isDirectory(translogPath)) {
            translogDirs.add(translogPath);
        }
    }
    return translogDirs;
}
项目:springrestdoc    文件:Swagger2MarkupTest.java   
@Test
public void createJsonFileFromSwaggerEndpoint() throws Exception {
    String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir"))
            .orElse("build/swagger");
    System.err.println(outputDir);
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"),
            StandardCharsets.UTF_8)) {
        writer.write(swaggerJson);
    }
}
项目:Java-for-Data-Science    文件:SentimentAnalysisTrainingData.java   
public static void main(String[] args) {
    try {
        String filename;
        String file;
        String text;
        List<String> lines = Files.readAllLines(Paths.get("C:\\Jenn Personal\\Packt Data Science\\Chapter 12\\Sentiment-Analysis-Dataset\\SentimentAnalysisDataset.csv"),StandardCharsets.ISO_8859_1);
        for(String s : lines){
            String[] oneLine = s.split(",");
            if(Integer.parseInt(oneLine[1])==1){
                filename = "pos";
            }else{
                filename = "neg";
            }
            file = oneLine[0]+".txt";
            text = oneLine[3];
            Files.write(Paths.get("C:\\Jenn Personal\\Packt Data Science\\Chapter 12\\review_polarity\\txt_sentoken\\"+filename+"\\"+file), text.getBytes());
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
项目:litiengine    文件:FileUtilities.java   
public static List<String> findFilesByExtension(final List<String> fileNames, final Path dir, final String extension) {
  try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (final Path path : stream) {
      if (path.toFile().isDirectory()) {
        if (isBlackListedDirectory(path)) {
          continue;
        }

        findFilesByExtension(fileNames, path, extension);
      } else if (path.toAbsolutePath().toString().endsWith(extension)) {
        fileNames.add(path.toAbsolutePath().toString());
      }
    }
  } catch (final IOException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }

  return fileNames;
}
项目:buenojo    文件:ImageCompletionLoader.java   
private void setImages(Path path, ImageCompletionExercise exercise, Boolean dryRun) throws BuenOjoDataSetException{
    try {

        Set<SatelliteImage> images = new HashSet<>(maxImages);
        List<Path> imageList = Files.walk(path, 1, FileVisitOption.FOLLOW_LINKS).filter(p-> {
            return BuenOjoFileUtils.contentType(p).isPresent() && !BuenOjoFileUtils.contentType(p).get().equals("text/csv")  && !isPlaceholderImage(p);
            }).collect(Collectors.toList());

        for (Path imagePath : imageList) {

            String fileName = FilenameUtils.removeExtension(imagePath.getFileName().toString());
            Path csvPath = path.resolve(fileName + FilenameUtils.EXTENSION_SEPARATOR+ BuenOjoFileUtils.CSV_EXTENSION);

            SatelliteImage image = satelliteImageFactory.imageFromFile(BuenOjoFileUtils.multipartFile(imagePath), BuenOjoFileUtils.multipartFile(csvPath), dryRun);
            images.add(image);

        }
        exercise.setSatelliteImages(new HashSet<>(satelliteImageRepository.save(images)));
    } catch (BuenOjoCSVParserException | InvalidSatelliteImageType | BuenOjoFileException | IOException
            | BuenOjoInconsistencyException e) {
        throw new BuenOjoDataSetException(e.getMessage());
    }
}
项目:elasticsearch_my    文件:InstallPluginCommandTests.java   
public void testBinPermissions() throws Exception {
    assumeTrue("posix filesystem", isPosix);
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path pluginDir = createPluginDir(temp);
    Path binDir = pluginDir.resolve("bin");
    Files.createDirectory(binDir);
    Files.createFile(binDir.resolve("somescript"));
    String pluginZip = createPlugin("fake", pluginDir);
    try (PosixPermissionsResetter binAttrs = new PosixPermissionsResetter(env.v2().binFile())) {
        Set<PosixFilePermission> perms = binAttrs.getCopyPermissions();
        // make sure at least one execute perm is missing, so we know we forced it during installation
        perms.remove(PosixFilePermission.GROUP_EXECUTE);
        binAttrs.setPermissions(perms);
        installPlugin(pluginZip, env.v1());
        assertPlugin("fake", pluginDir, env.v2());
    }
}
项目:grade-buddy    文件:Toolbar.java   
/**
 * Export the report.
 */
private void export() {
    final JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(this)) {
        final File file = new File(fc.getSelectedFile(), "report.csv");
        try {
            Files.write(
                Paths.get(file.getAbsolutePath()),
                new CsvReport(this.marking.submissions())
                    .report(true)
                    .getBytes()
            );
        } catch (IOException e1) {
            e1.printStackTrace();
            JOptionPane.showMessageDialog(
                this, e1.getMessage(), "Export error", JOptionPane.ERROR_MESSAGE);
        }
    }
}
项目:iopipe-java-core    文件:SystemMeasurement.java   
/**
 * Reads the first non-empty line for the given path.
 *
 * @param __p The path to read.
 * @param __def Default value if it could not be read.
 * @return The first non-empty line or {@code __def} if the file could not
 * be read or has only empty lines.
 * @throws NullPointerException On null arguments.
 * @since 2017/12/17
 */
private static String __readFirstLine(Path __p, String __def)
    throws NullPointerException
{
    if (__p == null)
        throw new NullPointerException();

    try
    {
        for (String l : Files.readAllLines(__p))
        {
            l = l.trim();
            if (!l.isEmpty())
                return l;
        }

        return __def;
    }

    catch (IOException e)
    {
        return __def;
    }
}
项目:CloudNet    文件:CloudConfig.java   
private void defaultInitDoc(ConsoleReader consoleReader) throws Exception
{
    if (Files.exists(servicePath)) return;

    String hostName = NetworkUtils.getHostName();
    if (hostName.equals("127.0.0.1") || hostName.equalsIgnoreCase("127.0.1.1") || hostName.split("\\.").length != 4)
    {
        String input;
        System.out.println("Please write the first Wrapper IP address:");
        while ((input = consoleReader.readLine()) != null)
        {
            if ((input.equals("127.0.0.1") || input.equalsIgnoreCase("127.0.1.1") || input.split("\\.").length != 4))
            {
                System.out.println("Please write the real ip address :)");
                continue;
            }

            hostName = input;
            break;
        }
    }
    new Document("wrapper", Arrays.asList(new WrapperMeta("Wrapper-1", hostName, "admin")))
            .append("serverGroups", Arrays.asList(new LobbyGroup()))
            .append("proxyGroups", Arrays.asList(new BungeeGroup()))
            .saveAsConfig(servicePath);
}
项目:jobson    文件:FilesystemUserDAO.java   
@Override
public boolean updateUserAuth(UserId id, String authName, String authField) {
    try {
        final List<UserCredentials> allCredentials = readUserCredentials().collect(Collectors.toList());

        final boolean userExists = allCredentials.stream().anyMatch(c -> c.getId().equals(id));

        if (userExists) {
            // TODO: Clean up
            final UserCredentials newUserCredentials = new UserCredentials(id, authName, authField);
            final Stream<UserCredentials> otherCredentials = allCredentials.stream().filter(c -> !c.getId().equals(id));
            final Stream<UserCredentials> upd = Stream.concat(otherCredentials, Stream.of(newUserCredentials));
            final String fileContent = String.join("", upd.map(c -> c + System.lineSeparator()).collect(Collectors.toList()));
            Files.write(usersFile.toPath(), fileContent.getBytes());
            return true;
        } else return false;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
项目:csap-core    文件:ServiceOsManager.java   
public File createVersionFile (
                                File versionFile, String version,
                                String userid, String description ) {

    String foundTime = LocalDateTime.now().format( DateTimeFormatter.ofPattern( "HH:mm:ss MMM d" ) );
    if ( version == null ) {
        version = LocalDateTime.now().format( DateTimeFormatter.ofPattern( "MMM.d-HH.mm" ) );
    }
    List<String> lines = Arrays.asList(
        "Deployment Notes",
        "<version>" + version + "</version>",
        description + " by: " + userid + " at " + foundTime );

    try {
        Files.write( versionFile.toPath(), lines, Charset.forName( "UTF-8" ) );
    } catch (IOException ex) {
        logger.error( "Failed creating version file", ex );
    }

    return versionFile;
}
项目:powsybl-core    文件:XMLImporterTest.java   
private void writeNetwork(String fileName, boolean writeExt) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(fileSystem.getPath(fileName), StandardCharsets.UTF_8)) {
        writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        writer.write("<iidm:network xmlns:iidm=\"http://www.itesla_project.eu/schema/iidm/1_0\" id=\"test\" caseDate=\"2013-01-15T18:45:00.000+01:00\" forecastDistance=\"0\" sourceFormat=\"test\">");
        writer.newLine();
        writer.write("    <iidm:substation id=\"P1\" country=\"FR\"/>");
        writer.newLine();
        if (writeExt) {
            writer.write("    <iidm:extension id=\"P1\">");
            writer.write("    <foo/>");
            writer.write("    </iidm:extension>");
        }
        writer.write("</iidm:network>");
        writer.newLine();
    }
}
项目:oscm    文件:EclipseProjectReader.java   
/**
 * Reads the path to the project from the Eclipse' .location meta data file.
 * This file can be found in
 * 'workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\
 * PROJECTNAME\.lo c a t i o n ' .<br />
 * The .location files is written with a special Outpustream and read with
 * an special InputStream implementation. You can find them in the eclipse
 * project org.eclipse.core.resource. The class names are<br />
 * org.eclipse.core.internal.localstore.SafeChunkyInputStream and <br />
 * org.eclipse.core.internal.localstore.SafeChunkyOutputStream.
 * <p>
 * The eclipse implementation which reads the .location file can be found in
 * the same project, the class name is
 * org.eclipse.core.internal.resources.LocalMetaArea, refer to method
 * readPrivateDescription.
 * <p>
 * Basically the first 16 bytes of the .location file are for consistency
 * reason there, the next bytes are the path to the project source. Those
 * bytes must be read via DataInputStream.readUTF.
 */
private String readFromLocationFile(File project) throws IOException {
    String result = "";
    Path location = Paths.get(project.getAbsolutePath())
            .resolve(".location");
    InputStream inputStream = Files.newInputStream(location);
    try (DataInputStream dataStream = new DataInputStream(inputStream);) {
        byte[] begin_chunk = new byte[16];
        dataStream.read(begin_chunk, 0, 16);
        result = dataStream.readUTF();

        String uriPrefix = "URI//file:";
        if (System.getProperty("os.name").startsWith("Windows")) {
            uriPrefix = uriPrefix.concat("/");
        }

        if (result.startsWith(uriPrefix)) {
            result = result.substring(uriPrefix.length());
        }
    }
    return result;
}
项目:AptSpring    文件:TestResourceLoader.java   
/**
 * Doesn't appear to work in docker, will never work in windows.
 * @throws IOException if any of the setup fails
 */
@Test
public void testBrokenEnvironment() throws IOException {
  File root = testFolder.newFolder();
  File workingDir = new File(root, FileStore.STANDARD.getPath() + File.separator);
  DefinitionModel model = new DefinitionModel(SIMPLE_MODEL);
  Files.createDirectories(workingDir.toPath(),
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(NO_PERMS)));
  if (PosixFilePermissions.fromString(NO_PERMS).equals(Files.getPosixFilePermissions(workingDir.toPath()))) {
    TestFileStore fileStore = new TestFileStore(root);
    assertThatThrownBy(() -> fileStore.store(model)).isInstanceOf(IOException.class)
      .hasMessage("could not write directories for model storage");
    Files.setPosixFilePermissions(workingDir.toPath(), PosixFilePermissions.fromString("rwxrwxrwx"));
  }
  cleanUp(root);
}
项目:ios-device-control    文件:SimulatorDeviceImpl.java   
@Override
public void installApplication(Path ipaOrAppPath) throws IosDeviceException {
  try {
    if (Files.isDirectory(ipaOrAppPath)) {
      await(simctl.install(ipaOrAppPath.toString()));
    } else {
      Path tmpDir = Files.createTempDirectory("app");
      try {
        unzipFile(ipaOrAppPath, tmpDir);
        Path appPath =
            tmpDir
                .resolve("Payload")
                .resolve(MoreFiles.getNameWithoutExtension(ipaOrAppPath) + ".app");
        await(simctl.install(appPath.toString()));
      } finally {
        MoreFiles.deleteRecursively(tmpDir, RecursiveDeleteOption.ALLOW_INSECURE);
      }
    }
  } catch (IOException e) {
    throw new IosDeviceException(this, e);
  }
}
项目:incubator-netbeans    文件:ApplyDiffPatchAction.java   
private static boolean isNetBeansPatch (File patchFile) {
    try (BufferedReader reader = Files.newBufferedReader(patchFile.toPath(), Charset.forName("UTF-8"))) {
        boolean netbeansPatch = false;
        boolean cont = true;
        for (String line = reader.readLine(); line != null && cont; line = reader.readLine()) {
            if (line.trim().isEmpty()) {
                // skip
            } else if (line.startsWith("#")) {
                line = line.substring(1).trim();
                if (line.startsWith(ExportDiffChangesAction.PATCH_FILE_HEADER)) {
                    // line was generated by NB HG diff action
                    netbeansPatch = true;
                    cont = false;
                }
            } else {
                // start of the patch file itself, NB header not found
                cont = false;
            }
        }
        return netbeansPatch;
    } catch (IOException ex) {
        return false;
    }
}
项目:security-karate    文件:CredentialFileParser.java   
public Optional<Stream<Credentials>> loadFile(Path filePath){
    if(filePath == null){
        return Optional.empty();
    }

    try{
        bufferedReader = Files.newBufferedReader(filePath);
        return Optional.of(bufferedReader.lines()
                .map(line -> extractCredentials(line, true))
                .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
        );
    } catch (IOException e) {
        logger.error("failed to load credentials from file.",e);
        return Optional.empty();
    }
}
项目:elasticsearch_my    文件:FileUtils.java   
private static void collectFiles(final Path dir, final String fileSuffix, final Map<String, Set<Path>> files) throws IOException {
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith(fileSuffix)) {
                String groupName = dir.relativize(file.getParent()).toString();
                Set<Path> filesSet = files.get(groupName);
                if (filesSet == null) {
                    filesSet = new HashSet<>();
                    files.put(groupName, filesSet);
                }
                filesSet.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
项目:smarti    文件:MongoDbMigrationService.java   
public void runDatabaseMigration() throws IOException {
    final ScriptOperations scriptOps = mongoTemplate.scriptOps();

    if (migrationProperties.getScriptHome() != null) {
        try {
            Files.list(migrationProperties.getScriptHome())
                    .filter(s -> migrationProperties.getPattern().matcher(s.getFileName().toString()).find())
                    .sorted(this::compareCaseInsensitive)
                    .forEachOrdered(s -> runDatabaseMigration(s, scriptOps));
        } catch (UncheckedIOException ex) {
            throw ex.getCause();
        }
    } else {
        log.error("smarti.migration.mongo.script-home not set - not running database migration!");
    }
}
项目:elasticsearch_my    文件:MetaDataStateFormat.java   
long findMaxStateId(final String prefix, Path... locations) throws IOException {
    long maxId = -1;
    for (Path dataLocation : locations) {
        final Path resolve = dataLocation.resolve(STATE_DIR_NAME);
        if (Files.exists(resolve)) {
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(resolve, prefix + "*")) {
                for (Path stateFile : stream) {
                    final Matcher matcher = stateFilePattern.matcher(stateFile.getFileName().toString());
                    if (matcher.matches()) {
                        final long id = Long.parseLong(matcher.group(1));
                        maxId = Math.max(maxId, id);
                    }
                }
            }
        }
    }
    return maxId;
}
项目:family-tree-xml-parser    文件:ScheduledFileReaderTest.java   
@Test
@SuppressWarnings("unchecked")
public void doNothingWhenPathCannotBeParsed() throws Exception {
  mockStatic(Files.class);

  when(validator.isValid(path)).thenReturn(true);

  DirectoryStream<Path> directoryStream = mock(DirectoryStream.class);
  when(Files.newDirectoryStream(path, "*.xml")).thenReturn(directoryStream);

  Iterator<Path> iterator = mock(Iterator.class);
  when(directoryStream.iterator()).thenReturn(iterator);

  when(iterator.hasNext()).thenReturn(true, false);
  Path file = mock(Path.class);
  when(iterator.next()).thenReturn(file);

  when(xmlParser.parseXml(file)).thenReturn(Optional.empty());

  scheduledFileReader.parseXmlFiles();

  verifyZeroInteractions(service);

  verifyStatic(Files.class);
  Files.newDirectoryStream(path, "*.xml");
}
项目:openjdk-jdk10    文件:DefaultImageBuilder.java   
/**
 * chmod ugo-w file
 */
private void setReadOnly(Path file) {
    try {
        Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
        perms.remove(PosixFilePermission.OWNER_WRITE);
        perms.remove(PosixFilePermission.GROUP_WRITE);
        perms.remove(PosixFilePermission.OTHERS_WRITE);
        Files.setPosixFilePermissions(file, perms);
    } catch (IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
}
项目:ats-framework    文件:LocalFileSystemOperations.java   
/**
 *
 * @param filename the file name
 * @return the file user id
 * @throws FileSystemOperationException
 */
private long getUserId(
                        String filename ) {

    try {
        Integer uid = ( Integer ) Files.getAttribute( new File( filename ).toPath(), "unix:uid",
                                                      LinkOption.NOFOLLOW_LINKS );
        return uid.longValue();

    } catch( Exception e ) {
        throw new FileSystemOperationException( "Could not get UID for '" + filename + "'", e );
    }
}
项目:openjdk-jdk10    文件:CreateSymbolsTestImpl.java   
void doTestEquivalence(String code7, String code8, String testClass) throws Exception {
    Path classes = prepareVersionedCTSym(code7, code8);
    Path classfile = classes.resolve("78").resolve(testClass.replace('.', '/') + ".class");

    if (!Files.isReadable(classfile)) {
        throw new AssertionError("Cannot find expected class.");
    }
}
项目:jdk8u-jdk    文件:PaddingTest.java   
private static void diff(String fname1, String fname2) throws Exception {
    if (!Arrays.equals(Files.readAllBytes(Paths.get(fname1)),
            Files.readAllBytes(Paths.get(fname2)))) {
        throw new Exception(
                "files " + fname1 + " and " + fname2 + " differ");
    }
}
项目:marathonv5    文件:Copy.java   
/**
 * Copy source file to target location.
 *
 * @return
 */
static boolean copyFile(Path source, Path target) {
    CopyOption[] options = new CopyOption[] { COPY_ATTRIBUTES, REPLACE_EXISTING };
    target = getUnique(target);
    try {
        Files.copy(source, target, options);
        return true;
    } catch (Exception x) {
        System.err.format("Unable to copy: %s: %s%n", source, x);
        return false;
    }
}
项目:uroborosql    文件:UroboroSQLTest.java   
@Test
public void builderWithSqlAgentFactory() throws Exception {
    SqlConfig config = UroboroSQL.builder("jdbc:h2:mem:SqlAgentTest", "", "")
            .setSqlAgentFactory(new SqlAgentFactoryImpl().setDefaultMapKeyCaseFormat(CaseFormat.CAMEL_CASE))
            .build();
    try (SqlAgent agent = config.agent()) {
        String[] sqls = new String(Files.readAllBytes(Paths.get("src/test/resources/sql/ddl/create_tables.sql")),
                StandardCharsets.UTF_8).split(";");
        for (String sql : sqls) {
            if (StringUtils.isNotBlank(sql)) {
                agent.updateWith(sql.trim()).count();
            }
        }

        insert(agent, Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));

        agent.query("example/select_product").paramList("product_id", 0, 1)
                .stream().forEach((m) -> {
                    assertTrue(m.containsKey("productId"));
                    assertTrue(m.containsKey("productName"));
                    assertTrue(m.containsKey("productKanaName"));
                    assertTrue(m.containsKey("janCode"));
                    assertTrue(m.containsKey("productDescription"));
                    assertTrue(m.containsKey("insDatetime"));
                    assertTrue(m.containsKey("updDatetime"));
                    assertTrue(m.containsKey("versionNo"));
                });

        agent.rollback();
    }

    assertEquals(new H2Dialect().getName(), config.getDialect().getName());
}
项目:write_api_service    文件:Publish.java   
/**
 * Gets the Output object from the filepath
 *
 * @param filePath The path to the file containing json output from the add command
 * @return The output object
 */
private static Output getJson(String filePath) {
    Output output = null;
    try {
        Path path = Paths.get(filePath);
        String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        Gson gson = new Gson();
        output = gson.fromJson(content, Output.class);
    } catch (IOException e) {
        ExceptionHelper.errorMessage(LOGGER, "Could not read json file" + e.getMessage(), ExceptionHelper.IO_ERROR);
    }
    return output;
}
项目:JavaRushTasks    文件:Solution.java   
public Class<?> load(Path path) {
    try {
        if (path.getFileName().toString().lastIndexOf(".class") == -1)
            return null;

        byte[] b = Files.readAllBytes(path);
        return defineClass(null, b, 0, b.length); //here main magic
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}