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

The following are Jave code examples for showing how to use toPath() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: minebox   File: SingleFileBucket.java   View Source Code Vote up 6 votes
SingleFileBucket(long bucketNumber, long bucketSize, Encryption encryption, File file) {
    this.bucketSize = bucketSize;
    this.bucketNumber = bucketNumber;
    this.encryption = encryption;
    baseOffset = bucketNumber * this.bucketSize;
    upperBound = baseOffset + this.bucketSize - 1;
    LOGGER.debug("starting to monitor bucket {} with file {}", bucketNumber, file.getAbsolutePath());
    this.file = file;
    try {
        filePath = file.toPath();
        final long existingFileSize = Files.size(filePath);
        this.fileWasZero = existingFileSize == 0;
        lastModifiedTime = Files.getLastModifiedTime(filePath);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 2
Project: neoscada   File: BaseWatcher.java   View Source Code Vote up 6 votes
public BaseWatcher ( final StorageManager storageManager, final File base ) throws IOException
{
    this.storageManager = storageManager;
    this.base = base.toPath ();
    this.watcher = FileSystems.getDefault ().newWatchService ();

    this.baseKey = base.toPath ().register ( this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE );

    logger.debug ( "Checking for initial storages" );

    for ( final File child : this.base.toFile ().listFiles () )
    {
        logger.debug ( "Found initial storage dir - {}", child );
        checkAddStorage ( child.toPath () );
    }

    startWatcher ();
}
 
Example 3
Project: openjdk-jdk10   File: SmokeTest.java   View Source Code Vote up 6 votes
static Path getTempFile(int size) throws IOException {
    File f = File.createTempFile("test", "txt");
    f.deleteOnExit();
    byte[] buf = new byte[2048];
    for (int i=0; i<buf.length; i++)
        buf[i] = (byte)i;

    FileOutputStream fos = new FileOutputStream(f);
    while (size > 0) {
        int amount = Math.min(size, buf.length);
        fos.write(buf, 0, amount);
        size -= amount;
    }
    fos.close();
    return f.toPath();
}
 
Example 4
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   View Source Code Vote up 6 votes
private static boolean isRemoteFS (FileObject fo) {
    if (!CHECK_REMOTE_FSTYPES) {
        return false;
    }
    if (!fo.isFolder()) {
        return false;
    }
    final File f = FileUtil.toFile(fo);
    if (f == null) {
        return false;
    }
    final Path p = f.toPath();
    try {
        final String fsType = Files.getFileStore(p).type();
        return REMOTE_FSTYPES.contains(fsType);
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
        return false;
    }
}
 
Example 5
Project: hearthstone   File: Dir.java   View Source Code Vote up 5 votes
/**
 * altera o longtime da última modificação no arquivo
 *
 * @param time data no formato longtime
 */
public static void setLastModifiedTime(File file, long time) {
    try {
        Path path = file.toPath();
        FileTime fileTime = FileTime.fromMillis(time);
        Files.setLastModifiedTime(path, fileTime);
    } catch (IOException ex) {
    }
}
 
Example 6
Project: helper   File: Configs.java   View Source Code Vote up 5 votes
@Nonnull
public static GsonConfigurationLoader gson(@Nonnull File file) {
    Path path = file.toPath();
    return GsonConfigurationLoader.builder()
            .setIndent(2)
            .setSource(() -> Files.newBufferedReader(path, StandardCharsets.UTF_8))
            .setSink(() -> Files.newBufferedWriter(path, StandardCharsets.UTF_8))
            .build();
}
 
Example 7
Project: NGB-master   File: FileManager.java   View Source Code Vote up 5 votes
/**
 * Creates index for a FeatureFile
 * @param featureFile a file to create index for
 * @return an index, represented by {@code SimpleFSDirectory} object
 * @throws IOException if something is wrong with access to file system
 */
public SimpleFSDirectory createIndexForFile(FeatureFile featureFile) throws IOException {
    final Map<String, Object> params = new HashMap<>();
    params.put(USER_ID.name(), featureFile.getCreatedBy());
    params.put(DIR_ID.name(), featureFile.getId());

    FilePathFormat format = determineFilePathFormat(featureFile);

    params.put(FEATURE_FILE_DIR.name(), substitute(format, params));
    File file = new File(toRealPath(substitute(FEATURE_INDEX_DIR, params)));

    return new SimpleFSDirectory(file.toPath());
}
 
Example 8
Project: n4js   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * Creates a new directory with the given parent folder and folder name. The newly created folder will be deleted on
 * graceful VM shutdown.
 *
 * @param parent
 *            the path of the parent folder.
 * @param folderName
 *            the name of the folder.
 * @return the path to the new directory.
 */
public static Path createDirectory(final Path parent, final String folderName) {
	final File file = new File(parent.toFile(), folderName);
	if (!file.exists()) {
		if (!file.mkdir()) {
			throw new RuntimeException(
					"Error while trying to create folder at " + parent + " with " + folderName + ".");
		}
	}
	file.deleteOnExit();
	return file.toPath();
}
 
Example 9
Project: n4js   File: EclipseExternalLibraryWorkspace.java   View Source Code Vote up 5 votes
@Override
public URI findProjectWith(URI nestedLocation) {
	final String path = nestedLocation.toFileString();
	if (null == path) {
		return null;
	}

	final File nestedResource = new File(path);
	if (!nestedResource.exists()) {
		return null;
	}

	final Path nestedResourcePath = nestedResource.toPath();

	final Iterable<URI> registeredProjectUris = projectCache.asMap().keySet();
	for (final URI projectUri : registeredProjectUris) {
		if (projectUri.isFile()) {
			final File projectRoot = new File(projectUri.toFileString());
			final Path projectRootPath = projectRoot.toPath();
			if (nestedResourcePath.startsWith(projectRootPath)) {
				return projectUri;
			}
		}
	}

	return null;
}
 
Example 10
Project: NGB-master   File: FileManager.java   View Source Code Vote up 5 votes
/**
 * Creates a {@code SimpleFSDirectory} object, representing a new Lucene index directory for feature index for
 * desired project ID
 *
 * @param projectId     an ID of a project, which feature index directory to fetch
 * @return an {@code SimpleFSDirectory} object, representing Lucene index directory for feature index
 * @throws IOException if something is wrong with access to file system
 */
public SimpleFSDirectory createIndexForProject(final long projectId) throws IOException {
    final Map<String, Object> params = new HashMap<>();
    params.put(PROJECT_ID.name(), projectId);

    File file = new File(toRealPath(substitute(PROJECT_FEATURE_INDEX_FILE, params)));

    return new SimpleFSDirectory(file.toPath());
}
 
Example 11
Project: Vanilla-Injection   File: ChatDemo.java   View Source Code Vote up 5 votes
@Override
public void onSetup(File log, File world) {
    try {
      connection = new InjectionConnection(log.toPath(), world.toPath(), "jarbot");
    } catch (IOException | InterruptedException ex) {
      throw new UndeclaredThrowableException(ex);
    }
    connection.getLogObserver().setLogCheckFrequency(500, MILLISECONDS);
    connection.setFlushFrequency(500, MILLISECONDS);

    connection.getLogObserver().addChatListener(l -> {
        if(l.getMessage().charAt(0) != '.') answer(Jarbot.ask(l.getMessage()));
    });
}
 
Example 12
Project: Hollow-Knight-SaveManager   File: Listeners.java   View Source Code Vote up 5 votes
@Override
public void actionPerformed(ActionEvent e){
	System.out.println("Save As activated");
	GUI.fc.setCurrentDirectory(new File(gui.savePath));
	int returnVal = GUI.fc.showOpenDialog(new JFrame("Save As..."));
	String path = gui.savePath;
	
       if (returnVal == JFileChooser.APPROVE_OPTION) {
       	
           File file = GUI.fc.getSelectedFile();
           File _src = new File(path+"/"+filename.getText());
           Path src = _src.toPath();
           try {
			if( !_src.exists() ){
				return;
			} else {
				Path cop = file.toPath();
				Files.copy(src, cop, StandardCopyOption.REPLACE_EXISTING);
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}

       } else {
       }
	gui.refreshFileTree(gui.savePath);
	System.out.println("Done");
}
 
Example 13
Project: incubator-netbeans   File: NbMavenProjectImpl.java   View Source Code Vote up 5 votes
public File[] getOtherRoots(boolean test) {
    URI uri = FileUtilities.getDirURI(getProjectDirectory(), test ? "src/test" : "src/main"); //NOI18N
    Set<File> toRet = new HashSet<File>();
    File fil = Utilities.toFile(uri);
    if (fil.exists()) {
        try {
            Path sourceRoot = fil.toPath();
            OtherRootsVisitor visitor = new OtherRootsVisitor(getLookup(), sourceRoot);
            Files.walkFileTree(sourceRoot, visitor);
            toRet.addAll(visitor.getOtherRoots());
        } catch (IOException ex) {
            // log as info to keep trace about possible problems, 
            // but lets not be too agressive with level and notification                
            // see also issue #251071
            LOG.log(Level.INFO, null, ex);
        }
    }
    URI[] res = getResources(test);
    for (URI rs : res) {
        File fl = Utilities.toFile(rs);
        //in node view we need only the existing ones, if anything else needs all,
        // a new method is probably necessary..
        if (fl.exists()) {
            toRet.add(fl);
        }
    }
    return toRet.toArray(new File[0]);
}
 
Example 14
Project: incubator-netbeans   File: MultiModuleGroupQueryImpl.java   View Source Code Vote up 4 votes
public MultiModuleGroupQuery.Result findModuleInfo(SourceGroup grp) {
    MultiModuleGroupQuery.Result res;
    
    synchronized (this) {
        res = cachedModuleInfo.get(grp);
        if (res != null) {
            return res == NONE ? null : res;
        }
    }
    int ver = version.get();
    Set<String> props = new HashSet<>();
    Set<FileObject> newmodRoots = new HashSet<>();
    for (Roots r : roots) {
        if (!RootsAccessor.getInstance().isSourceRoot(r)) {
            continue;
        }
        FileObject groot = grp.getRootFolder();
        File rootFile = FileUtil.toFile(groot);
        Path rootPath = rootFile.toPath();
        String[] propNames = r.getRootProperties();
        String[] rootPathPropNames = RootsAccessor.getInstance().getRootPathProperties(r);
        for (int i = 0; i < propNames.length; i++) {
            final String prop = propNames[i];
            final String pathProp = rootPathPropNames[i];
            final String type = RootsAccessor.getInstance().getType(r);

            if (pathProp == null || JavaProjectConstants.SOURCES_TYPE_MODULES.equals(type)) {  //NOI18N
                continue;
            }
            final String pathToModules = evaluator.getProperty(prop);
            final String loc = evaluator.getProperty(pathProp);
            final File file = helper.resolveFile(pathToModules);
            props.add(prop);
            final Collection<? extends String> spVariants = Arrays.stream(PropertyUtils.tokenizePath(loc))
                    .map((p) -> CommonModuleUtils.parseSourcePathVariants(p))
                    .flatMap((lv) -> lv.stream())
                    .collect(Collectors.toList());
            for (File f : file.listFiles()) {
                if (!f.isDirectory()) {
                    continue;
                }
                for (String variant : spVariants) {
                    final String pathInModule = variant;
                    FileObject rfo = FileUtil.toFileObject(file);
                    if (rfo != null) {
                        newmodRoots.add(rfo);
                    }
                    Path fPath = file.toPath();
                    if (rootPath.startsWith(fPath)) {
                        Path rel = fPath.relativize(rootPath);
                        Path intra = Paths.get(pathInModule);
                        String modName = rel.getName(0).toString();
                        if (!pathInModule.isEmpty()) {
                            if (rel.getNameCount() == 1 ||
                                !rel.subpath(1, rel.getNameCount()).equals(intra)) {
                                continue;
                            }
                        }
                        MultiModuleGroupQuery.Result fres = new MultiModuleGroupQuery.Result(modName, pathInModule);
                        synchronized (this) {
                            if (ver == version.get()) {
                                return cachedModuleInfo.computeIfAbsent(grp, (g) -> fres);
                            } else {
                                return fres;
                            }
                        }
                    }
                }
            }
        }
    }
    synchronized (this) {
        if (ver == version.get() && !cachedModuleInfo.containsKey(grp)) {
            cachedModuleInfo.put(grp, NONE);
            watchedProperties.addAll(props);
        }
    }
    return null;
}
 
Example 15
Project: instalint   File: DefaultPluginJarExploderTest.java   View Source Code Vote up 4 votes
Path getFileFromCache(String filename) throws IOException {
  File src = FileUtils.toFile(getClass().getResource("/" + filename));
  File destFile = new File(new File(userHome, "" + filename.hashCode()), filename);
  FileUtils.copyFile(src, destFile);
  return destFile.toPath();
}
 
Example 16
Project: L2J-Global   File: ScriptEngineManager.java   View Source Code Vote up 4 votes
private void processFile(File file, Map<IExecutionContext, List<Path>> files)
{
	switch (file.getName())
	{
		case "package-info.java":
		case "MasterHandler.java":
		case "EffectMasterHandler.java":
		case "SkillConditionMasterHandler.java":
		case "ConditionMasterHandler.java":
		case "DailyMissionMasterHandler.java":
		{
			return;
		}
	}
	
	Path sourceFile = file.toPath();
	try
	{
		checkExistingFile("ScriptFile", sourceFile);
	}
	catch (Exception e)
	{
		LOGGER.warning(e.getMessage());
		return;
	}
	
	sourceFile = sourceFile.toAbsolutePath();
	final String ext = getFileExtension(sourceFile);
	if (ext == null)
	{
		LOGGER.warning("ScriptFile: " + sourceFile + " does not have an extension to determine the script engine!");
		return;
	}
	
	final IExecutionContext engine = getEngineByExtension(ext);
	if (engine == null)
	{
		return;
	}
	
	files.computeIfAbsent(engine, k -> new LinkedList<>()).add(sourceFile);
}
 
Example 17
Project: CSLMusicModStationCreator   File: MainWindow.java   View Source Code Vote up 4 votes
private void exportStation(File target) {

        if(!station.hasSaveLocation()) {
            DialogHelper.showErrorAlert("Export music pack", "You need to save the station once.");
            return;
        }

        if(!saveFile()){
            return;
        }

        try {
            List<File> export = station.getExportableFiles();

            Path exportroot = target.toPath();
            Path sourceroot = exportroot.resolve("Source");
            Path stationroot = exportroot.resolve("CSLMusicMod_Music");

            if(!Files.exists(sourceroot)) {
                Files.createDirectory(sourceroot);
            }
            if(!Files.exists(stationroot)) {
                Files.createDirectory(stationroot);
            }

            Files.write(sourceroot.resolve("Mod.cs"), station.buildModSource().getBytes(Charsets.UTF_8), StandardOpenOption.CREATE);

            Path stationdefinitionroot = Paths.get(station.getDirectory());

            CopyTask task = new CopyTask(export.stream().map(file -> {
                return new CopyTask.Entry(file, stationroot.resolve(stationdefinitionroot.relativize(file.toPath())).toFile());
            }).collect(Collectors.toList()));
            task.runningProperty().addListener((observableValue, aBoolean, t1) -> {
                root.setDisable(t1);
                progress.setVisible(t1);
            });
            progress.progressProperty().unbind();
            progress.progressProperty().bind(task.progressProperty());
            new Thread(task).start();

        } catch (IOException e) {
            DialogHelper.showExceptionError("Export music pack", "Error while exporting the music pack!", e);
        }
    }
 
Example 18
Project: openjdk-jdk10   File: ZipFSTester.java   View Source Code Vote up 4 votes
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 19
Project: spring-rest-basis   File: AbstractZg2proRestTemplate.java   View Source Code Vote up 3 votes
/**
 *
 * post a file to a service, the post is executed in a pseudo-streaming
 * mode, which means TCP segments are sent toward the url immediately as
 * soon as the sufficient data is read inside the input file. So you will
 * not have any problem with memory management especially if you have to
 * deal with big files.
 * <b>NB:</b> handling your headers by an interceptor would slow down your
 * query execution, hence if you have to use headers, another method will
 * accept them as arguments. By the way, even the LoggingRequestInterceptor
 * should not be used here
 * <b>NB:</b> also you should know Path from java.nio is known to be more
 * performant than File from java.io and can provide all File class
 * capabilities
 *
 * When the upload is finished, your file will be deleted from your disk
 * space
 *
 * @param <T>: the return type of the webmethod
 * @param url: the url toward which a file (digital object) will be sent
 * @param file: the file to upload toward the service
 * @param returnType: the return type of the webmethod
 * @return
 * @throws java.io.IOException
 */
public <T> T postForFileAndDelete(String url, File file, Class<T> returnType) throws IOException {
    Path p = file.toPath();
    T response = postForPathPrivate(p, url, returnType);
    Files.delete(p);
    return response;
}
 
Example 20
Project: bibliome-java-utils   File: Trie.java   View Source Code Vote up 2 votes
/**
 * Loads a trie saved with save().
 * @param file
 * @param valueDecoder
 * @throws IOException
 */
public Trie(File file, Decoder<T> valueDecoder) throws IOException {
	this(file.toPath(), valueDecoder);
}