Java Code Examples for java.io.File#toPath()

The following examples show how to use java.io.File#toPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FieldSetAccessibleTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
Stream<String> folderToStream(String folderName) {
    final File root = new File(folderName);
    if (root.canRead() && root.isDirectory()) {
        final Path rootPath = root.toPath();
        try {
            return Files.walk(rootPath)
                .filter(p -> p.getFileName().toString().endsWith(".class"))
                .map(rootPath::relativize)
                .map(p -> p.toString().replace(File.separatorChar, '/'));
        } catch (IOException x) {
            x.printStackTrace(System.err);
            skipped.add(folderName);
        }
    } else {
        cantread.add(folderName);
    }
    return Collections.<String>emptyList().stream();
}
 
Example 2
Source File: BlobContainerTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFiles() throws Exception {
    File blobsPath = temporaryFolder.newFolder();
    BlobContainer blobContainer = new BlobContainer(blobsPath.toPath());
    blobContainer.getFile(digest("Content A")).createNewFile();
    blobContainer.getFile(digest("Content B")).createNewFile();
    blobContainer.getFile(digest("Content C")).createNewFile();

    Iterator<File> fileIterator = blobContainer.getFiles().iterator();

    assertThat(fileIterator.hasNext(), is(true));
    assertThat(fileIterator.next().exists(), is(true));
    assertThat(fileIterator.hasNext(), is(true));
    assertThat(fileIterator.next().exists(), is(true));
    assertThat(fileIterator.next().exists(), is(true));
    assertThat(fileIterator.hasNext(), is(false));
}
 
Example 3
Source File: ODirectFileOutputStreamTest.java    From herddb with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleArrayBiggerThanTwoBlockSize() throws Exception {
    int blocksize;
    File file = tmp.newFile();
    byte[] test;
    ODirectFileOutputStream _oo;
    try (ODirectFileOutputStream oo = new ODirectFileOutputStream(file.toPath())) {
        _oo = oo;
        blocksize = oo.getAlignment();
        test = new byte[blocksize + blocksize + blocksize / 2];
        Arrays.fill(test, (byte) 6);
        oo.write(test);
    }
    byte[] read = Files.readAllBytes(file.toPath());
    assertArrayEquals(test, Arrays.copyOf(read, test.length));
    assertEquals(blocksize * 3, read.length);
    assertEquals(3, _oo.getWrittenBlocks());
}
 
Example 4
Source File: NodeSettingsTest.java    From crate with Apache License 2.0 6 votes vote down vote up
private Path createConfigPath() throws IOException {
    File config = tmp.newFolder("crate", "config");

    HashMap<String, String> pathSettings = new HashMap<>();
    pathSettings.put(PATH_DATA_SETTING.getKey(), tmp.newFolder("crate", "data").getPath());
    pathSettings.put(PATH_LOGS_SETTING.getKey(), tmp.newFolder("crate", "logs").getPath());

    try (Writer writer = new FileWriter(Paths.get(config.getPath(), "crate.yml").toFile())) {
        Yaml yaml = new Yaml();
        yaml.dump(pathSettings, writer);
    }

    new FileOutputStream(new File(config.getPath(), "log4j2.properties")).close();

    return config.toPath();
}
 
Example 5
Source File: BlockMerge.java    From ariADDna with Apache License 2.0 6 votes vote down vote up
public File concateBlockInFile(Metafile metafile, Set<Block> blockSet) throws IOException {
    File localFile = localService.getLocalFileByUuid(metafile.getFileUuid());
    FileOutputStream outputStream = new FileOutputStream(localFile);

    //int off = 0;
    for (Block block : blockSet) {

        int size = block.getPayload().length;
        outputStream.write(block.getPayload(), 0, size);
        //off += size;
    }
    Map<String, String> attributes = metafile.getProperties();
    for (Map.Entry<String, String> entry : attributes.entrySet()) {
        Path path = localFile.toPath();
        Files.setAttribute(path, entry.getKey(), entry.getValue());
    }
    return localFile;
}
 
Example 6
Source File: GeneListOutputRendererUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Whitebox test making sure that the internal state of the geneExonToVCFuncotaitonMap is consistent.
 * Does not test default annotations, override annotations, or excluded fields.
 */
@Test(dataProvider = "provideGeneExonMapTest")
public void testWriteGeneExonToVariantFuncotationMap(SortedMap<Pair<String,String>, Pair<VariantContext, FuncotationMap>> gtMap,
    final VariantContext segmentVariantContext, final FuncotationMap funcotationMap) throws IOException {
    final File outputFile = File.createTempFile("simpleSegFileWriting", ".seg");

    final GeneListOutputRenderer geneListOutputRenderer = new GeneListOutputRenderer(outputFile.toPath(), new LinkedHashMap<>(),
            new LinkedHashMap<>(), new HashSet<>(), "TEST_TOOL");

    geneListOutputRenderer.write(segmentVariantContext, funcotationMap);
    final SortedMap<Pair<String,String>, Pair<VariantContext, FuncotationMap>> sortedMap = geneListOutputRenderer.getGeneExonToVariantFuncotationMap();
    Assert.assertEquals(sortedMap, gtMap);
}
 
Example 7
Source File: TestGetFile.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testPath() throws IOException {
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/", Locale.US);
    final String dirStruc = sdf.format(new Date());

    final File directory = new File("target/test/data/in/" + dirStruc);
    deleteDirectory(new File("target/test/data/in"));
    assertTrue("Unable to create test data directory " + directory.getAbsolutePath(), directory.exists() || directory.mkdirs());

    final File inFile = new File("src/test/resources/hello.txt");
    final Path inPath = inFile.toPath();
    final File destFile = new File(directory, inFile.getName());
    final Path targetPath = destFile.toPath();
    final Path absTargetPath = targetPath.toAbsolutePath();
    final String absTargetPathStr = absTargetPath.getParent().toString() + "/";
    Files.copy(inPath, targetPath);

    final TestRunner runner = TestRunners.newTestRunner(new GetFile());
    runner.setProperty(GetFile.DIRECTORY, "target/test/data/in");
    runner.run();

    runner.assertAllFlowFilesTransferred(GetFile.REL_SUCCESS, 1);
    final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(GetFile.REL_SUCCESS);
    successFiles.get(0).assertContentEquals("Hello, World!".getBytes("UTF-8"));

    final String path = successFiles.get(0).getAttribute("path");
    assertEquals(dirStruc, path.replace('\\', '/'));
    final String absolutePath = successFiles.get(0).getAttribute(CoreAttributes.ABSOLUTE_PATH.key());
    assertEquals(absTargetPathStr, absolutePath);
}
 
Example 8
Source File: UIUtil.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * A replacement for standard JFileChooser, to allow better look and feel on the Mac
 * platform.
 *
 * @param save      true for a SAVE dialog, false for a LOAD dialog
 * @param parent    the parent component for the dialog, if any
 * @param startPath default path, or just default directory, or null
 * @param filter    a filter to be applied on files
 * @param title     a specific dialog title or null
 * @return the selected file, or null
 */
public static Path pathChooser (boolean save,
                                Component parent,
                                Path startPath,
                                OmrFileFilter filter,
                                String title)
{
    File file = fileChooser(save, parent, startPath.toFile(), filter, null);

    if (file != null) {
        return file.toPath();
    }

    return null;
}
 
Example 9
Source File: ArtifactManagerTest.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public Path write(String fileName, List<String> lines) {
  try {
    File file = cacheDir.toPath().resolve(fileName).toFile();
    Path path = file.toPath();
    Files.write(path, lines, Charset.forName("UTF-8"));
    return path;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 10
Source File: CustomSystemClassLoader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Class<?> defineFinderClass(String name)
    throws ClassNotFoundException {
    final Object obj = getClassLoadingLock(name);
    synchronized(obj) {
        if (finderClass != null) return finderClass;

        URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
        File file = new File(url.getPath(), name+".class");
        if (file.canRead()) {
            try {
                byte[] b = Files.readAllBytes(file.toPath());
                Permissions perms = new Permissions();
                perms.add(new AllPermission());
                finderClass = defineClass(
                        name, b, 0, b.length, new ProtectionDomain(
                        this.getClass().getProtectionDomain().getCodeSource(),
                        perms));
                System.out.println("Loaded " + name);
                return finderClass;
            } catch (Throwable ex) {
                ex.printStackTrace();
                throw new ClassNotFoundException(name, ex);
            }
        } else {
            throw new ClassNotFoundException(name,
                    new IOException(file.toPath() + ": can't read"));
        }
    }
}
 
Example 11
Source File: AbstractControllerService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void deleteFile(File file) throws IOException {
    if (file != null) {
        Path path = file.toPath();
        if (Files.exists(path)) {
            Files.delete(path);
        }
    }
}
 
Example 12
Source File: DockerAccessWithHcClient.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void copyArchive(String containerId, File archive, String targetPath)
        throws DockerAccessException {
    try {
        String url = urlBuilder.copyArchive(containerId, targetPath);
        delegate.put(url, archive, HTTP_OK);
    } catch (IOException e) {
        throw new DockerAccessException(e, "Unable to copy archive %s to container [%s] with path %s",
                archive.toPath(), containerId, targetPath);
    }
}
 
Example 13
Source File: FileWatcherFileSystemService.java    From diirt with MIT License 5 votes vote down vote up
Registration(File file, Runnable callback) throws IOException {
    this.file = file;
    this.callback = callback;
    this.path = file.toPath();
    this.watchService = path.getFileSystem().newWatchService();
    this.path.getParent().register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
}
 
Example 14
Source File: CreateHadoopBamSplittingIndexIntegrationTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(dataProvider = "indexable")
public void testUnspecifiedOutputProducesAdjacentIndex(final File bam) throws IOException {
    // copy the bam file to a new temp file
    // we're going to write an index next to it on disk, and we don't want to write into the test resources folder
    final File bamCopy = createTempFile("copy-"+bam, ".bam");
    Files.copy(bam.toPath(), bamCopy.toPath(), StandardCopyOption.REPLACE_EXISTING);
    final File expectedIndex = new File(bamCopy.toPath() + FileExtensions.SBI);
    Assert.assertFalse(expectedIndex.exists());
    final ArgumentsBuilder args = new ArgumentsBuilder().addInput(bamCopy);
    this.runCommandLine(args);
    expectedIndex.deleteOnExit();
    assertIndexIsNotEmpty(expectedIndex);
}
 
Example 15
Source File: AtlasDesugarTransform.java    From atlas with Apache License 2.0 4 votes vote down vote up
/**
 * Set this location of extracted desugar jar that is used for processing.
 */
private static void initDesugarJar(@Nullable FileCache cache) throws IOException {
    if (isDesugarJarInitialized()) {
        return;
    }

    URL url = DesugarProcessBuilder.class.getClassLoader().getResource(DESUGAR_JAR);
    Preconditions.checkNotNull(url);

    Path extractedDesugar = null;
    if (cache != null) {
        try {
            String fileHash;
            try (HashingInputStream stream =
                         new HashingInputStream(Hashing.sha256(), url.openStream())) {
                fileHash = stream.hash().toString();
            }
            FileCache.Inputs inputs =
                    new FileCache.Inputs.Builder(FileCache.Command.EXTRACT_DESUGAR_JAR)
                            .putString("pluginVersion", Version.ANDROID_GRADLE_PLUGIN_VERSION)
                            .putString("jarUrl", url.toString())
                            .putString("fileHash", fileHash)
                            .build();

            File cachedFile =
                    cache.createFileInCacheIfAbsent(
                            inputs, file -> copyDesugarJar(url, file.toPath()))
                            .getCachedFile();
            Preconditions.checkNotNull(cachedFile);
            extractedDesugar = cachedFile.toPath();
        } catch (IOException | ExecutionException e) {
            logger.error(e, "Unable to cache Desugar jar. Extracting to temp dir.");
        }
    }

    synchronized (desugarJar) {
        if (isDesugarJarInitialized()) {
            return;
        }

        if (extractedDesugar == null) {
            extractedDesugar = PathUtils.createTmpToRemoveOnShutdown(DESUGAR_JAR);
            copyDesugarJar(url, extractedDesugar);
        }
        desugarJar.set(extractedDesugar);
    }
}
 
Example 16
Source File: ZipFSTester.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static Path getTempPath() throws IOException
{
    File tmp = File.createTempFile("testzipfs_", "zip");
    tmp.delete();    // we need a clean path, no file
    return tmp.toPath();
}
 
Example 17
Source File: DefaultAccessLogReceiver.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public DefaultAccessLogReceiver(final Executor logWriteExecutor, final File outputDirectory, final String logBaseName) {
    this(logWriteExecutor, outputDirectory.toPath(), logBaseName, null);
}
 
Example 18
Source File: CheckLockLocationTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Setup all the files and directories needed for the tests
 *
 * @return writable directory created that needs to be deleted when done
 * @throws RuntimeException
 */
private static File setup() throws RuntimeException {
    // First do some setup in the temporary directory (using same logic as
    // FileHandler for %t pattern)
    String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
    if (tmpDir == null) {
        tmpDir = System.getProperty("user.home");
    }
    File tmpOrHomeDir = new File(tmpDir);
    // Create a writable directory here (%t/writable-dir)
    File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
    if (!createFile(writableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " writable working directory "
                + writableDir.getAbsolutePath() );
    }
    // writableDirectory and its contents will be deleted after the test
    // that uses it

    // Create a plain file which we will attempt to use as a directory
    // (%t/not-a-dir)
    File notAdir = new File(tmpOrHomeDir, NOT_A_DIR);
    if (!createFile(notAdir, false)) {
        throw new RuntimeException("Test setup failed: unable to a plain"
                + " working file " + notAdir.getAbsolutePath() );
    }
    notAdir.deleteOnExit();

    // Create a non-writable directory (%t/non-writable-dir)
    File nonWritableDir = new File(tmpOrHomeDir, NON_WRITABLE_DIR);
    if (!createFile(nonWritableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " a non-"
                + "writable working directory "
                + nonWritableDir.getAbsolutePath() );
    }
    nonWritableDir.deleteOnExit();

    // make it non-writable
    Path path = nonWritableDir.toPath();
    final boolean nonWritable = nonWritableDir.setWritable(false);
    final boolean isWritable = Files.isWritable(path);
    if (nonWritable && !isWritable) {
        runNonWritableDirTest = true;
        System.out.println("Created non writable dir for "
                + getOwner(path) + " at: " + path.toString());
    } else {
        runNonWritableDirTest = false;
        System.out.println( "Test Setup WARNING: unable to make"
                + " working directory " + nonWritableDir.getAbsolutePath()
                + "\n\t non-writable for " + getOwner(path)
                +  " on platform " + System.getProperty("os.name"));
    }

    // make sure non-existent directory really doesn't exist
    File nonExistentDir = new File(tmpOrHomeDir, NON_EXISTENT_DIR);
    if (nonExistentDir.exists()) {
        nonExistentDir.delete();
    }
    System.out.println("Setup completed - writableDir is: " + writableDir.getPath());
    return writableDir;
}
 
Example 19
Source File: DirectoryService.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
public Path getSaveOutputPath(FileChooser.ExtensionFilter extensionFilter, boolean askPath) {

        if (!Platform.isFxApplicationThread()) {
            final CompletableFuture<Path> completableFuture = new CompletableFuture<>();

            completableFuture.runAsync(() -> {
                threadService.runActionLater(() -> {
                    try {
                        Path outputPath = getSaveOutputPath(extensionFilter, askPath);
                        completableFuture.complete(outputPath);
                    } catch (Exception e) {
                        completableFuture.completeExceptionally(e);
                    }
                });
            }, threadService.executor());

            return completableFuture.join();
        }

        boolean isNew = current.currentTab().isNew();

        if (isNew) {
            controller.saveDoc();
        }

        final Path currentTabPath = current.currentPath().get();
        final Path currentTabPathDir = currentTabPath.getParent();
        String tabText = current.getCurrentTabText().replace("*", "").trim();
        tabText = tabText.contains(".") ? tabText.split("\\.")[0] : tabText;

        if (!askPath) {
            return currentTabPathDir.resolve(extensionFilter.getExtensions().get(0).replace("*", tabText));
        }

        final FileChooser fileChooser = this.newFileChooser(String.format("Save %s file", extensionFilter.getDescription()));
        fileChooser.getExtensionFilters().addAll(extensionFilter);
        File file = fileChooser.showSaveDialog(null);

        if (Objects.isNull(file)) {
            return currentTabPathDir.resolve(extensionFilter.getExtensions().get(0).replace("*", tabText));
        }

        return file.toPath();
    }
 
Example 20
Source File: SequenceNumberIndexWriter.java    From artio with Apache License 2.0 4 votes vote down vote up
public SequenceNumberIndexWriter(
    final AtomicBuffer inMemoryBuffer,
    final MappedFile indexFile,
    final ErrorHandler errorHandler,
    final int streamId,
    final RecordingIdLookup recordingIdLookup,
    final long indexFileStateFlushTimeoutInMs,
    final EpochClock clock,
    final String metaDataDir,
    final Long2LongHashMap connectionIdToILinkUuid)
{
    this.inMemoryBuffer = inMemoryBuffer;
    this.indexFile = indexFile;
    this.errorHandler = errorHandler;
    this.streamId = streamId;
    this.fileCapacity = indexFile.buffer().capacity();
    this.indexFileStateFlushTimeoutInMs = indexFileStateFlushTimeoutInMs;
    this.clock = clock;

    iLinkSequenceNumberExtractor = new ILinkSequenceNumberExtractor(
        connectionIdToILinkUuid, errorHandler,
        (seqNum, uuid, messageSize, endPosition, aeronSessionId) ->
        saveRecord(seqNum, uuid, endPosition, NO_REQUIRED_POSITION));

    final String indexFilePath = indexFile.file().getAbsolutePath();
    indexPath = indexFile.file().toPath();
    final File writeableFile = writableFile(indexFilePath);
    writablePath = writeableFile.toPath();
    passingPlacePath = passingFile(indexFilePath).toPath();
    writableFile = MappedFile.map(writeableFile, fileCapacity);
    sequenceNumberExtractor = new SequenceNumberExtractor(errorHandler);

    // TODO: Fsync parent directory
    indexedPositionsOffset = positionTableOffset(fileCapacity);
    checksumFramer = new ChecksumFramer(
        inMemoryBuffer, indexedPositionsOffset, errorHandler, 0, "SequenceNumberIndex");
    try
    {
        initialiseBuffer();
        positionWriter = new IndexedPositionWriter(
            positionsBuffer(inMemoryBuffer, indexedPositionsOffset),
            errorHandler,
            indexedPositionsOffset,
            "SequenceNumberIndex",
            recordingIdLookup);

        if (metaDataDir != null)
        {
            metaDataLocation = metaDataFile(metaDataDir);
            metaDataFile = openMetaDataFile(metaDataLocation);
        }
        else
        {
            metaDataLocation = null;
            metaDataFile = null;
        }
    }
    catch (final Exception e)
    {
        CloseHelper.close(writableFile);
        indexFile.close();
        throw e;
    }
}