Example usage for java.io File toPath

List of usage examples for java.io File toPath

Introduction

In this page you can find the example usage for java.io File toPath.

Prototype

public Path toPath() 

Source Link

Document

Returns a Path java.nio.file.Path object constructed from this abstract path.

Usage

From source file:net.sf.jasperreports.repo.DefaultRepositoryService.java

@Override
public ResourceInfo getResourceInfo(RepositoryContext context, String location) {
    //detecting URLs
    URL url = JRResourcesUtil.createURL(location, urlHandlerFactory);
    if (url != null) {
        //not supporting paths relative to URLs
        return null;
    }//from www.ja v a  2s.  c om

    if (fileResolver != null) {
        //not dealing with file resolvers
        return null;
    }

    File file = resolveFile(context, location);
    if (file != null) {
        try {
            //resolving to real path to eliminate .. and .
            Path path = file.toPath().toRealPath();
            return StandardResourceInfo.from(path);
        } catch (IOException e) {
            log.warn("Failed to resolve real path for file " + file, e);

            //using the paths as present in the File object
            return StandardResourceInfo.from(file);
        }
    }

    //TODO lucianc classloader resources
    return null;
}

From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testAnnotateFileContentsDescClient() throws Exception {
    File f = new File("test-file");
    try {//from  w w w  .j  a va 2 s .co m
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);
        AnnotatedDocument result = apiDesc.annotateFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertTrue(result.getText().contains("Barack"));
    } finally {
        f.delete();
    }
}

From source file:com.ontotext.s4.service.S4ServiceClientIntegrationTest.java

@Test
public void testAnnotateFileContentsUrlClient() throws Exception {
    File f = new File("test-file");
    try {/*w  w  w . j  a v a2s .c om*/
        Path p = f.toPath();
        ArrayList<String> lines = new ArrayList<>(1);
        lines.add(documentText);
        Files.write(p, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE);
        AnnotatedDocument result = apiUrl.annotateFileContents(f, Charset.forName("UTF-8"), documentMimeType);
        assertTrue(result.getText().contains("Barack"));
    } finally {
        f.delete();
    }
}

From source file:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Copied the files from DMIs ftp server to the local machine
 *
 * @return a Map with a local file and the time the file was created on the FTP server
 *//*from   w  w  w  .j a  va 2 s.  com*/
private Map<File, Instant> transferFilesIfNeeded(FTPClient client, String directoryName, List<FTPFile> files)
        throws IOException {

    File current = new File(tempDirLocation, directoryName);
    if (newestDirectories.isEmpty()) {
        // If we just started check if there is data from an earlier run and delete it
        File temp = new File(tempDirLocation);
        if (temp.exists()) {
            File[] oldFolders = temp.listFiles(new PatternFilenameFilter(FOLDER_PATTERN));
            if (oldFolders != null) {
                List<File> foldersToDelete = Lists.newArrayList(oldFolders);
                foldersToDelete.remove(current);
                for (File oldFolder : foldersToDelete) {
                    log.info("deleting old GRIB folder {}", oldFolder);
                    deleteRecursively(oldFolder);
                }
            }
        }
    }

    if (!current.exists()) {
        if (!current.mkdirs()) {
            throw new IOException("Unable to create temp directory " + current.getAbsolutePath());
        }
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    Map<File, Instant> transferred = new HashMap<>();
    for (FTPFile file : files) {
        File tmp = new File(current, file.getName());
        if (tmp.exists()) {
            long localSize = Files.size(tmp.toPath());
            if (localSize != file.getSize()) {
                log.info("deleting {} local file has size {}, remote is {}", tmp.getName(), localSize,
                        file.getSize());
                if (!tmp.delete()) {
                    log.warn("Unable to delete " + tmp.getAbsolutePath());
                }
            } else {
                // If the file has the right size we assume it was copied correctly (otherwise we needed to hash them)
                log.info("Reusing already downloaded version of {}", tmp.getName());
                transferred.put(tmp, file.getTimestamp().toInstant());
                continue;
            }
        }
        if (tmp.createNewFile()) {
            log.info("downloading {}", tmp.getName());

            // this often fails with java.net.ConnectException: Operation timed out
            int count = 0;
            while (count++ < MAX_TRIES) {
                try (FileOutputStream fout = new FileOutputStream(tmp)) {
                    client.retrieveFile(file.getName(), fout);
                    fout.flush();
                    break;
                } catch (IOException e) {
                    log.warn(String.format("Failed to transfer file %s, try number %s", file.getName(), count),
                            e);
                }
            }
        } else {
            throw new IOException("Unable to create temp file on disk.");
        }

        transferred.put(tmp, file.getTimestamp().toInstant());
    }
    log.info("transferred weather files in {} ms", stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
    return transferred;
}

From source file:FileGameAccess.java

@Override
public void clearPersistance() {
    File folder = new File(System.getProperty("user.dir"));
    File[] filesInFolder = folder.listFiles();
    List<User> users = new ArrayList<>();
    for (File f : filesInFolder)
        if (FilenameUtils.getExtension(f.getName()).equals("commands")
                || FilenameUtils.getExtension(f.getName()).equals("catanmodel"))
            try {
                Files.delete(f.toPath());
            } catch (IOException ex) {
                Logger.getLogger(FileGameAccess.class.getName()).log(Level.SEVERE, null, ex);
            }/*from  w ww. j ava2  s .c  o m*/

}

From source file:com.ejisto.event.listener.SessionRecorderManager.java

private WebApplicationDescriptor createTempWebApplicationDescriptor(WebApplicationDescriptor original)
        throws IOException, JDOMException {
    Path path = Files.createTempDirectory(original.getContextPath().replaceAll("/", "_"));
    unzipFile(original.getWarFile(), path.toString());
    File targetDir = new File(FilenameUtils.normalize(path.toString() + "/WEB-INF/lib/"));
    copyEjistoLibs(true, targetDir.toPath());
    WebApplicationDescriptor temp = WebApplicationDescriptor.copyOf(original);
    temp.setDeployablePath(path.toString());
    modifyWebXml(temp);//from   ww w.j a  va 2  s . c  o  m
    return temp;
}

From source file:com.oracle.javawc.entities.shell.FileLoaderTest.java

/**
 * Test of loadFile method, of class FileLoader.
 *//* ww  w  . j  a  v a  2s.  c om*/
@Test
public void testLoadFile_Path() throws Exception {
    File file1 = testFolder.newFile("file1.txt");

    Collection<String> input = new ArrayList<>();
    Collections.addAll(input, "word1 word2 word3", "word1 word2 word3");
    FileUtils.writeLines(file1, Charset.forName("UTF-8").name(), input, true);

    Path path = file1.toPath();
    FileLoader instance = new FileLoader();
    List<String> lines = instance.loadFile(path);
    WordCount wc = new WordCount();

    assertThat(wc.countLines(lines)).isEqualTo(2);
    assertThat(wc.countWords(lines)).isEqualTo(6);
    assertThat(wc.countAvgLettersPerWords(lines)).isEqualTo(5);
    assertThat(wc.mostCommonLetter(lines)).isEqualTo("d");

}

From source file:com.oracle.javawc.entities.shell.FileLoaderTest.java

/**
 * Test of loadFile method, of class FileLoader.
 *///from ww  w . ja  va  2 s .  com
@Test
public void testLoadFile_Path_Charset() throws Exception {
    File file1 = testFolder.newFile("file1.txt");

    Collection<String> input = new ArrayList<>();
    Collections.addAll(input, "word1 word2 word3", "word1 word2 word3");
    FileUtils.writeLines(file1, Charset.forName("UTF-8").name(), input, true);

    Path path = file1.toPath();
    FileLoader instance = new FileLoader();
    WordCount result = new WordCount();
    List<String> lines = instance.loadFile(path, Charset.forName("UTF-8"));

    assertThat(result).isNotNull();
    assertThat(result.countLines(lines)).isEqualTo(2);
    assertThat(result.countWords(lines)).isEqualTo(6);
    assertThat(result.countAvgLettersPerWords(lines)).isEqualTo(5);
    assertThat(result.mostCommonLetter(lines)).isEqualTo("d");
}

From source file:org.n52.sensorweb.series.policy.editor.srv.impl.XmlFileSimplePermissionService.java

private String getCheckedConfiguredFile() throws IOException {
    URL url = getClass().getResource(getPermissionFile());
    if (url == null) {
        LOGGER.info("Permissions File: '" + permissionFile + "'");
        File file = new File(getPermissionFile());
        writer.createEmptyPermissionFileIfNotExist(file);
        permissionFile = file.toPath().toString();
        return permissionFile;
    }//from w w  w  .  j  a  v  a  2s . co  m
    return url.getFile();
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Write the properties object to the specified file.
 *
 * @param properties an instance of a {@link java.util.Properties} object.
 * @param file       the file that the properties will be written to.
 * @param message    the message that is included in the header of properties files.
 * @throws IOException an {@link java.io.IOException} if their was a problem writing to the file.
 *///from www.  j av  a2s.c o  m
default void writeToFile(Properties properties, File file, String message) throws IOException {
    Validate.notNull(properties);
    Validate.notNull(file);
    Validate.notNull(message);

    writeToFile(properties, file.toPath(), message);

}