java.nio.file.Path#toFile ( )源码实例Demo

下面列出了java.nio.file.Path#toFile ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@BeforeEach
protected void before(TestInfo testInfo) throws Exception {
    init();
    File repoBaseFolder = tempDir.toFile();

    // place repo in a sym-linked folder if requested by the concrete test class
    if (useSymLinkedFolder) {
        Path linkTarget = repoBaseFolder.toPath().resolve("link-target");
        Path link = repoBaseFolder.toPath().resolve("link");
        Files.createDirectory(linkTarget);

        // - creation of most links requires elevated rights on windows, including the ones
        //   created by Files.createSymbolicLink()
        // - creation of junctions should work without elevated rights but can only be created
        //   via mklink.exe /J ...
        if (SystemUtils.IS_OS_WINDOWS) {
            ProcessUtils.startAndWaitForProcess("mklink", "/J", link.toAbsolutePath().toString(), linkTarget.toAbsolutePath().toString());
        } else {
            Files.createSymbolicLink(link, linkTarget);
        }

        repoBaseFolder = link.toFile();
    }
    localRepoMock = new LocalRepoMock(repoBaseFolder, remoteRepoServerType);
    repoPath = localRepoMock.getBaseCanonicalBaseFolder().toPath();
}
 
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    String fn = file.getFileName().toString();
    // Skip pyc and pyi files.
    if (fn.endsWith(".pyc") || fn.endsWith(".pyi"))
        return FileVisitResult.CONTINUE;
    
    String entryName = rootEntryName;
    String relativePath = start.relativize(file).toString();
    // If empty, file is the start file.
    if(!relativePath.isEmpty()){                          
        entryName = entryName + "/" + relativePath;
    }
    // Zip uses forward slashes
    entryName = entryName.replace(File.separatorChar, '/');
    
    ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName);
    if (Files.isExecutable(file))
        entry.setUnixMode(0100770);
    else
        entry.setUnixMode(0100660);

    zos.putArchiveEntry(entry);
    Files.copy(file, zos);
    zos.closeArchiveEntry();
    return FileVisitResult.CONTINUE;
}
 
源代码3 项目: SubServers-2   文件: Metrics.java
/**
 * Gets the first bStat Metrics class.
 *
 * @return The first bStats metrics class.
 */
private Class<?> getFirstBStatsClass() {
    Path configPath = new File(plugin.dir, "plugins").toPath().resolve("bStats");
    configPath.toFile().mkdirs();
    File tempFile = new File(configPath.toFile(), "temp.txt");

    try {
        String className = readFile(tempFile);
        if (className != null) {
            try {
                // Let's check if a class with the given name exists.
                return Class.forName(className);
            } catch (ClassNotFoundException ignored) { }
        }
        writeFile(tempFile, getClass().getName());
        return getClass();
    } catch (IOException e) {
        if (logFailedRequests) {
            plugin.getLogger().log(Level.WARNING, "Failed to get first bStats class!", e);
        }
        return null;
    }
}
 
源代码4 项目: ache   文件: FilesTargetRepository.java
private synchronized void openNewFile() throws IOException {
    if(currentFile != null) {
        // flush and automatically closes file
        try(OutputStream out = this.currentFile) {
            out.flush();
        }
    }
    long timestamp = System.currentTimeMillis();
    long count = 0;
    Path filePath;
    do {
        String file = String.format("crawl_data-%d-%d.deflate", timestamp, count++);
        filePath = directory.resolve(file);
    } while (Files.exists(filePath));
    OutputStream fileStream = new PrintStream(filePath.toFile());
    this.bytesCounter = new CountingOutputStream(fileStream);
    this.currentFile = new DeflaterOutputStream(this.bytesCounter, true);
}
 
源代码5 项目: CodeDefenders   文件: FileUtilsTest.java
@Test
public void testExtractFileNameWithoutExtension() {
    String name = "TestName";

    Path tempDirectory;
    try {
        tempDirectory = Files.createTempDirectory("extension-test");
    } catch (IOException e) {
        Assume.assumeNoException(e);
        return;
    }
    File file = new File(tempDirectory.toFile(), name);
    String result = FileUtils.extractFileNameNoExtension(file.toPath());

    Assert.assertEquals(name, result);

    Assume.assumeTrue(tempDirectory.toFile().delete());
}
 
源代码6 项目: reef   文件: REEFScheduler.java
private String getReefTarUri(final String jobIdentifier) {
  try {
    // Create REEF_TAR
    final FileOutputStream fileOutputStream = new FileOutputStream(REEF_TAR);
    final TarArchiveOutputStream tarArchiveOutputStream =
        new TarArchiveOutputStream(new GZIPOutputStream(fileOutputStream));
    final File globalFolder = new File(this.fileNames.getGlobalFolderPath());
    final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(globalFolder.toPath());

    for (final Path path : directoryStream) {
      tarArchiveOutputStream.putArchiveEntry(new TarArchiveEntry(path.toFile(),
          globalFolder + "/" + path.getFileName()));

      final BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path.toFile()));
      IOUtils.copy(bufferedInputStream, tarArchiveOutputStream);
      bufferedInputStream.close();

      tarArchiveOutputStream.closeArchiveEntry();
    }
    directoryStream.close();
    tarArchiveOutputStream.close();
    fileOutputStream.close();

    // Upload REEF_TAR to HDFS
    final FileSystem fileSystem = FileSystem.get(new Configuration());
    final org.apache.hadoop.fs.Path src = new org.apache.hadoop.fs.Path(REEF_TAR);
    final String reefTarUriValue = fileSystem.getUri().toString() + this.jobSubmissionDirectoryPrefix + "/" +
        jobIdentifier + "/" + REEF_TAR;
    final org.apache.hadoop.fs.Path dst = new org.apache.hadoop.fs.Path(reefTarUriValue);
    fileSystem.copyFromLocalFile(src, dst);

    return reefTarUriValue;
  } catch (final IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码7 项目: synthea   文件: ChartRendererTest.java
@Test
public void testRenderFileFromPerson() throws Exception {
  tmpFolder.create();
  
  Path tmpFilePath = Paths.get(tmpFolder.getRoot().getAbsolutePath(), "tmp.png");
  
  Person person = new Person(0L);
  TimeSeriesData data1 = new TimeSeriesData(1.0);
  data1.addValue(3.5);
  data1.addValue(3.9);
  data1.addValue(4.3);
  data1.addValue(4.8);
  person.attributes.put("attr1", data1);
  
  PersonChartConfig chartCfg = new PersonChartConfig();
  chartCfg.setAxisLabelX("Time");
  chartCfg.setAxisAttributeX("time");
  chartCfg.setFilename(tmpFilePath.toString());
  chartCfg.setType("scatter");
  
  PersonSeriesConfig seriesCfg = new PersonSeriesConfig();
  seriesCfg.setAttribute("attr1");
  
  ArrayList<PersonSeriesConfig> seriesList = new ArrayList<PersonSeriesConfig>();
  seriesList.add(seriesCfg);
  
  chartCfg.setSeries(seriesList);
  
  ChartRenderer.drawChartAsFile(person, chartCfg);
  
  // Verify that the image file was created
  File imgFile = tmpFilePath.toFile();
  
  assertTrue("image file created", imgFile.exists());
  assertTrue("image file not empty", imgFile.length() > 0);
}
 
源代码8 项目: uyuni   文件: MinionPillarManagerTest.java
public void testGeneratePillarForServerGPGCheckOn() throws Exception {
    MinionServer minion = MinionServerFactoryTest.createTestMinionServer(user);
    Channel channel1 = ChannelTestUtils.createBaseChannel(user);
    minion.addChannel(channel1);
    ServerFactory.save(minion);

    minionPillarManager.generatePillar(minion);

    Path filePath = tmpPillarRoot
            .resolve(PILLAR_DATA_FILE_PREFIX + "_" + minion.getMinionId() + "." + PILLAR_DATA_FILE_EXT);

    assertTrue(Files.exists(filePath));

    Map<String, Object> map;
    try (FileInputStream fi = new FileInputStream(filePath.toFile())) {
        map = new Yaml().loadAs(fi, Map.class);
    }

    Map<String, Object> channels = (Map<String, Object>) map.get("channels");
    assertEquals(1, channels.size());
    assertTrue(channels.containsKey(channel1.getLabel()));

    Map<String, Object> values = (Map<String, Object>) channels.get(channel1.getLabel());

    assertTrue(values.containsKey("pkg_gpgcheck"));
    assertEquals("1", (String) values.get("pkg_gpgcheck"));
}
 
源代码9 项目: qpid-jms   文件: SaslGssApiIntegrationTest.java
@BeforeClass
public static void setUpKerberos() throws Exception {
    servicePrincipal = prepareServiceName();
    LOG.info("Using service principal: " + servicePrincipal);

    Path targetDir = FileSystems.getDefault().getPath("target");
    Path tempDirectory = Files.createTempDirectory(targetDir, "junit.SaslGssApiIntegrationTest.");
    File root = tempDirectory.toFile();

    kdc = new MiniKdc(MiniKdc.createConf(), new File(root, "kdc"));
    kdc.start();

    // hard coded match, default_keytab_name in minikdc-krb5.conf template
    File userKeyTab = new File(KRB5_KEYTAB);
    kdc.createPrincipal(userKeyTab, CLIENT_PRINCIPAL_LOGIN_CONFIG, CLIENT_PRINCIPAL_FACTORY_USERNAME,
            CLIENT_PRINCIPAL_URI_USERNAME, CLIENT_PRINCIPAL_DEFAULT_CONFIG_SCOPE, servicePrincipal);

    if (DEBUG) {
        Keytab kt = Keytab.read(userKeyTab);
        for (KeytabEntry entry : kt.getEntries()) {
            LOG.info("KeyTab Entry: PrincipalName:" + entry.getPrincipalName() + " ; KeyInfo:"+ entry.getKey().getKeyType());
        }

        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("javax.security.sasl");
        logger.setLevel(java.util.logging.Level.FINEST);
        logger.addHandler(new java.util.logging.ConsoleHandler());
        for (java.util.logging.Handler handler : logger.getHandlers()) {
            handler.setLevel(java.util.logging.Level.FINEST);
        }
    }
}
 
源代码10 项目: openjdk-jdk9   文件: RequestProcessors.java
static FileInputStream create(Path name) {
    try {
        return new FileInputStream(name.toFile());
    } catch (FileNotFoundException e) {
        throw new UncheckedIOException(e);
    }
}
 
源代码11 项目: nifi-minifi   文件: FileBasedVariableRegistry.java
public FileBasedVariableRegistry(final Path[] propertiesPaths) {
    final Map<VariableDescriptor, String> newMap = new HashMap<>(VariableRegistry.ENVIRONMENT_SYSTEM_REGISTRY.getVariableMap());
    final int systemEnvPropCount = newMap.size();
    int totalPropertiesLoaded = systemEnvPropCount;
    LOG.info("Loaded {} properties from system properties and environment variables",systemEnvPropCount);
    try {
        for (final Path path : propertiesPaths) {
            if (Files.exists(path)) {
                final AtomicInteger propsLoaded = new AtomicInteger(0);
                try (final InputStream inStream = new BufferedInputStream(new FileInputStream(path.toFile()))) {
                    Properties properties = new Properties();
                    properties.load(inStream);
                    properties.entrySet().stream().forEach((entry) -> {
                        final VariableDescriptor desc = new VariableDescriptor.Builder(entry.getKey().toString())
                                .description(path.toString())
                                .sensitive(false)
                                .build();
                        newMap.put(desc, entry.getValue().toString());
                        propsLoaded.incrementAndGet();
                    });
                }
                totalPropertiesLoaded += propsLoaded.get();
                if(propsLoaded.get() > 0){
                    LOG.info("Loaded {} properties from '{}'", propsLoaded.get(), path);
                }else{
                    LOG.warn("No properties loaded from '{}'", path);
                }
            } else {
                LOG.warn("Skipping property file {} as it does not appear to exist", path);
            }
        }
    } catch (final IOException ioe) {
        LOG.error("Unable to complete variable registry loading from files due to ", ioe);
    }
    LOG.info("Loaded a total of {} properties.  Including precedence overrides effective accessible registry key size is {}", totalPropertiesLoaded, newMap.size());
    map = newMap;
}
 
public static void main(String[] args) throws Exception {
	
	
	Path path = Paths.get("./test-out/nio-test.txt");
	File file = path.toFile();
	file.delete();
	file.createNewFile();
	
	ArrayList<Task> list = new ArrayList<>();
	for (int i = 0; i < taskCount; i++) {
		list.add(new Task(path, i+1));
	}
	
		
	for (Task task : list) {
		task.writeAsync();
	}
	
	//wait end
	synchronized (endObject) {
		try {
			if(endCount != taskCount) endObject.wait();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	System.out.println("end");
	
}
 
源代码13 项目: openjdk-jdk9   文件: InitialContextTest.java
private static Path createFactoryFrom(Path srcTemplate,
                                      String factoryFqn,
                                      Path dstFolder) throws IOException {

    String factorySimpleName, packageName;
    int i = factoryFqn.lastIndexOf('.');
    if (i < 0) {
        packageName = "";
        factorySimpleName = factoryFqn;
    } else {
        packageName = factoryFqn.substring(0, i);
        factorySimpleName = factoryFqn.substring(i + 1);
    }

    Path result = dstFolder.resolve(factorySimpleName + ".java");
    File dst = result.toFile();
    File src = srcTemplate.toFile();
    try (BufferedReader r = new BufferedReader(new FileReader(src));
         BufferedWriter w = new BufferedWriter(new FileWriter(dst))) {

        List<String> lines = processTemplate(packageName, factorySimpleName,
                r.lines()).collect(Collectors.toList());

        Iterator<String> it = lines.iterator();
        if (it.hasNext())
            w.write(it.next());
        while (it.hasNext()) {
            w.newLine();
            w.write(it.next());
        }
    }
    return result;
}
 
源代码14 项目: dekorate   文件: WithKubernetesConfig.java
default KubernetesConfig getKubernetesConfig(Path path) {
  File f = path.toFile();
  if (f.exists()) {
    try (InputStream is = new FileInputStream(f))  {
      return Serialization.unmarshal(is, KubernetesConfig.class);
    } catch (IOException e) {
      throw DekorateException.launderThrowable(e);
    }
  }

  throw new IllegalStateException("Expected to find kubernetes config at: " + path + "!");
}
 
@Override
public void deleteUserStores(String[] domains) throws IdentityUserStoreMgtException {

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    Path path;
    if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
        path = Paths.get(DEPLOYMENT_DIRECTORY);
    } else {
        path = Paths.get(CarbonUtils.getCarbonTenantsDirPath(), String.valueOf(tenantId), USERSTORES);
    }
    File file = path.toFile();
    for (String domainName : domains) {
        if (log.isDebugEnabled()) {
            log.debug("Deleting, .... " + domainName + " domain.");
        }
        try {
            // Run pre user-store name update listeners
            triggerListnersOnUserStorePreDelete(domainName);
            // Delete persisted domain name
            deletePersitedDomain(tenantId, domainName);
        } catch (UserStoreException e) {
            String errorMessage = "Error while deleting user store : " + domainName;
            log.error(errorMessage, e);
            throw new IdentityUserStoreMgtException(errorMessage);
        }
        // Delete file
        deleteFile(file, domainName.replace(".", "_").concat(".xml"));
    }
}
 
源代码16 项目: snap-desktop   文件: OpenLocalProductsRunnable.java
@Override
protected Void execute() throws Exception {
    for (int i = 0; i<this.productsToProcess.size(); i++) {
        LocalRepositoryProduct repositoryProduct = (LocalRepositoryProduct)this.productsToProcess.get(i);
        try {
            updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.OPENING);

            // check if the local product exists on the disk
            if (Files.exists(repositoryProduct.getPath())) {
                // the product exists on the local disk

                //TODO Jean temporary method until the Landsat8 product reader will be changed to read the product from a folder
                Path productPath = RemoteProductsRepositoryProvider.prepareProductPathToOpen(repositoryProduct.getPath(), repositoryProduct);
                File productFile = productPath.toFile();

                //TODO Jean old code to get the product path to open
                //File productFile = repositoryProduct.getPath().toFile();

                ProductReader productReader = ProductIO.getProductReaderForInput(productFile);
                if (productReader == null) {
                    // no product reader found in the application
                    updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_OPENED_MISSING_PRODUCT_READER);
                } else {
                    // there is a product reader in the application
                    Product product = productReader.readProductNodes(productFile, null);
                    if (product == null) {
                        // the product has not been read
                        throw new NullPointerException("The product '" + repositoryProduct.getName()+"' has not been read from '" + productFile.getAbsolutePath()+"'.");
                    } else {
                        // open the product in the application
                        Runnable runnable = new PairRunnable<LocalRepositoryProduct, Product>(repositoryProduct, product) {
                            @Override
                            protected void execute(LocalRepositoryProduct localRepositoryProduct, Product productToOpen) {
                                appContext.getProductManager().addProduct(productToOpen); // open the product in the application
                                updateProductProgressStatusLater(localRepositoryProduct, LocalProgressStatus.OPENED);
                            }
                        };
                        SwingUtilities.invokeLater(runnable);
                    }
                }
            } else {
                // the product does not exist into the local repository folder
                updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.MISSING_PRODUCT_FROM_REPOSITORY);
            }
        } catch (Exception exception) {
            updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_OPENED);
            logger.log(Level.SEVERE, "Failed to open the local product '" + repositoryProduct.getURL() + "'.", exception);
        }
    }
    return null;
}
 
源代码17 项目: app-gradle-plugin   文件: NullSafeTest.java
@Test
public void testConvert_value() {
  Path testPath = Paths.get("some/path");
  File expectedResult = testPath.toFile();
  Assert.assertEquals(expectedResult, NullSafe.convert(testPath, Path::toFile));
}
 
@Transactional(rollbackOn = {Exception.class})
public void export(LunchVoucherMgt lunchVoucherMgt) throws IOException {
  MetaFile metaFile = new MetaFile();
  metaFile.setFileName(
      I18n.get("LunchVoucherCommand")
          + " - "
          + LocalDate.now().format(DateTimeFormatter.ISO_DATE)
          + ".csv");

  Path tempFile = MetaFiles.createTempFile(null, ".csv");
  final OutputStream os = new FileOutputStream(tempFile.toFile());

  try (final Writer writer = new OutputStreamWriter(os)) {

    List<String> header = new ArrayList<>();
    header.add(escapeCsv(I18n.get("Company code")));
    header.add(escapeCsv(I18n.get("Lunch Voucher's number")));
    header.add(escapeCsv(I18n.get("Employee")));
    header.add(escapeCsv(I18n.get("Lunch Voucher format")));

    writer.write(Joiner.on(";").join(header));

    for (LunchVoucherMgtLine lunchVoucherMgtLine : lunchVoucherMgt.getLunchVoucherMgtLineList()) {

      List<String> line = new ArrayList<>();
      line.add(escapeCsv(lunchVoucherMgt.getCompany().getCode()));
      line.add(escapeCsv(lunchVoucherMgtLine.getLunchVoucherNumber().toString()));
      line.add(escapeCsv(lunchVoucherMgtLine.getEmployee().getName()));
      line.add(
          escapeCsv(lunchVoucherMgtLine.getEmployee().getLunchVoucherFormatSelect().toString()));

      writer.write("\n");
      writer.write(Joiner.on(";").join(line));
    }

    Beans.get(MetaFiles.class).upload(tempFile.toFile(), metaFile);

  } catch (Exception e) {
    Throwables.propagate(e);
  } finally {
    Files.deleteIfExists(tempFile);
  }
  /*
   */
  // lunchVoucherMgt.setExported(true);
  lunchVoucherMgt.setCsvFile(metaFile);
  lunchVoucherMgt.setExportDate(Beans.get(AppBaseService.class).getTodayDate());

  lunchVoucherMgtRepository.save(lunchVoucherMgt);
}
 
源代码19 项目: nifi   文件: MinimalLockingWriteAheadLog.java
/**
 *
 * @param paths a sorted set of Paths to use for the partitions/journals and
 * the snapshot. The snapshot will always be written to the first path
 * specified.
 * @param partitionCount the number of partitions/journals to use. For best
 * performance, this should be close to the number of threads that are
 * expected to update the repository simultaneously
 * @param serdeFactory the factory for the serializer/deserializer for records
 * @param syncListener the listener
 * @throws IOException if unable to initialize due to IO issue
 */
@SuppressWarnings("unchecked")
public MinimalLockingWriteAheadLog(final SortedSet<Path> paths, final int partitionCount, final SerDeFactory<T> serdeFactory, final SyncListener syncListener) throws IOException {
    this.syncListener = syncListener;

    requireNonNull(paths);
    requireNonNull(serdeFactory);

    if (paths.isEmpty()) {
        throw new IllegalArgumentException("Paths must be non-empty");
    }

    int resolvedPartitionCount = partitionCount;
    int existingPartitions = 0;
    for (final Path path : paths) {
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }

        final File file = path.toFile();
        if (!file.isDirectory()) {
            throw new IOException("Path given [" + path + "] is not a directory");
        }
        if (!file.canWrite()) {
            throw new IOException("Path given [" + path + "] is not writable");
        }
        if (!file.canRead()) {
            throw new IOException("Path given [" + path + "] is not readable");
        }
        if (!file.canExecute()) {
            throw new IOException("Path given [" + path + "] is not executable");
        }

        final File[] children = file.listFiles();
        if (children != null) {
            for (final File child : children) {
                if (child.isDirectory() && child.getName().startsWith("partition-")) {
                    existingPartitions++;
                }
            }

            if (existingPartitions != 0 && existingPartitions != partitionCount) {
                logger.warn("Constructing MinimalLockingWriteAheadLog with partitionCount={}, but the repository currently has "
                        + "{} partitions; ignoring argument and proceeding with {} partitions",
                        new Object[]{partitionCount, existingPartitions, existingPartitions});
                resolvedPartitionCount = existingPartitions;
            }
        }
    }

    this.basePath = paths.iterator().next();
    this.partialPath = basePath.resolve("snapshot.partial");
    this.snapshotPath = basePath.resolve("snapshot");
    this.serdeFactory = serdeFactory;

    final Path lockPath = basePath.resolve("wali.lock");
    lockChannel = new FileOutputStream(lockPath.toFile()).getChannel();
    lockChannel.lock();

    partitions = new Partition[resolvedPartitionCount];

    Iterator<Path> pathIterator = paths.iterator();
    for (int i = 0; i < resolvedPartitionCount; i++) {
        // If we're out of paths, create a new iterator to start over.
        if (!pathIterator.hasNext()) {
            pathIterator = paths.iterator();
        }

        final Path partitionBasePath = pathIterator.next();

        partitions[i] = new Partition<>(partitionBasePath.resolve("partition-" + i), serdeFactory, i, getVersion());
    }
}
 
private Future<File> createCodeArchive(File toolkitRoot, JsonObject submission, String mainCompositeKind) throws IOException, URISyntaxException {
    
    String tkName = toolkitRoot != null ? toolkitRoot.getName() : null;
            
    Path zipOutPath = pack(toolkitRoot, submission, tkName, mainCompositeKind);
    
    if (keepBuildArchive || keepArtifacts(submission)) {
    	final JsonObject submissionResult = GsonUtilities.objectCreate(submission, RemoteContext.SUBMISSION_RESULTS);
    	submissionResult.addProperty(SubmissionResultsKeys.ARCHIVE_PATH, zipOutPath.toString());
    }
            
    return new CompletedFuture<File>(zipOutPath.toFile());
}