当前位置: 首页>>代码示例>>Java>>正文


Java Path.toFile方法代码示例

本文整理汇总了Java中java.nio.file.Path.toFile方法的典型用法代码示例。如果您正苦于以下问题:Java Path.toFile方法的具体用法?Java Path.toFile怎么用?Java Path.toFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.file.Path的用法示例。


在下文中一共展示了Path.toFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: removeAbsoluteUrls

import java.nio.file.Path; //导入方法依赖的package包/类
@Nullable
public TempBlob removeAbsoluteUrls(final TempBlob tempBlob,
                                   final Repository repository) {
  try {
    Path tempFile = createTempFile("conan-download_url-" + randomUUID().toString(), "json");

    try {
      try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile.toFile()))) {
        String input = IOUtils.toString(tempBlob.get());
        input = input.replaceAll(CONAN_BASE_URL, repository.getUrl());
        bufferedWriter.write(input);
      }
      return convertFileToTempBlob(tempFile, repository);
    } finally {
      delete(tempFile);
    }
  } catch (IOException e) {
    log.warn("Unable to create temp file");
  }
  return null;
}
 
开发者ID:sonatype-nexus-community,项目名称:nexus-repository-conan,代码行数:22,代码来源:ConanAbsoluteUrlRemover.java

示例2: MakeNewBP

import java.nio.file.Path; //导入方法依赖的package包/类
public static void MakeNewBP(Player player, VirtualTool vt) {
    final Path filePath = Paths.get(vt.getBackpackPath() + File.separator + player.getUniqueId().toString() + ".backpack");
    final File file = filePath.toFile();

    final Path oldfilePath = Paths.get(vt.getBackpackPath() + File.separator + player.getUniqueId().toString() + ".json");
    final File oldfile = oldfilePath.toFile();

    if (oldfile.exists()) {
        Tools.ConvertBP(player, vt);
    } else {
        if (!file.exists()) {
            if (!Tools.WriteFile(file, "{}", vt)) {
                vt.getLogger().error("Failed to create backpack file on player join for " + player.getName());
            }
        }
    }
}
 
开发者ID:poqdavid,项目名称:VirtualTool,代码行数:18,代码来源:Tools.java

示例3: getFirstBStatsClass

import java.nio.file.Path; //导入方法依赖的package包/类
/**
 * Gets the first bStat Metrics class.
 *
 * @return The first bStats metrics class.
 */
private Class<?> getFirstBStatsClass() {
    Path configPath = configDir.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) {
            logger.warn("Failed to get first bStats class!", e);
        }
        return null;
    }
}
 
开发者ID:Lergin,项目名称:Vigilate,代码行数:28,代码来源:Metrics.java

示例4: valid

import java.nio.file.Path; //导入方法依赖的package包/类
@Test
public void valid()
    throws InvalidDataException, IOException, UnsupportedTagException {
    final Path path = Paths.get(
        "src/test/resources/testTempAlbumCover.jpg"
    );
    Files.write(
        path,
        new AdvancedTagFromMp3File(
            new Mp3File(
                new File("src/test/resources/album/test.mp3")
            )
        ).construct().getAlbumImage()
    );
    final File actual = path.toFile();
    actual.deleteOnExit();
    MatcherAssert.assertThat(
        "Album cover image from tag did not match the original one",
        FileUtils.contentEquals(
            actual,
            new File("src/test/resources/album/albumCover.jpg")
        ),
        Matchers.equalTo(true)
    );
}
 
开发者ID:driver733,项目名称:VKMusicUploader,代码行数:26,代码来源:AdvancedTagFromMp3FileTest.java

示例5: saveToDisk

import java.nio.file.Path; //导入方法依赖的package包/类
private void saveToDisk() {
  if (recording == null) {
    // Nothing to save
    return;
  }
  try {
    Path file = Storage.createRecordingFilePath(startTime);
    if (recordingFile == null) {
      recordingFile = file.toFile();
    }
    Serialization.saveRecording(recording, file);
    log.fine("Saved recording to " + file);
  } catch (IOException e) {
    throw new RuntimeException("Could not save the recording", e);
  }
}
 
开发者ID:wpilibsuite,项目名称:shuffleboard,代码行数:17,代码来源:Recorder.java

示例6: handle

import java.nio.file.Path; //导入方法依赖的package包/类
@Override
public void handle(Context ctx) throws Exception {
    final RamlModelRepository ramlModelRepository = ctx.get(RamlModelRepository.class);
    final Path filePath = ramlModelRepository.getFilePath();
    final Path parent = ramlModelRepository.getParent();
    final String path = ctx.getPathBinding().getPastBinding();

    final Path resolvedFilePath = path.isEmpty() ? filePath : parent.resolve(path).normalize();
    final File file = resolvedFilePath.toFile();
    if (file.exists()) {
        final String content;
        if (QueryParams.resolveIncludes(ctx)) {
            content = new IncludeResolver().preprocess(resolvedFilePath).toString();
        } else {
            content = Files.asByteSource(file).asCharSource(Charsets.UTF_8).read();
        }
        ctx.byContent(byContentSpec -> byContentSpec
                .type("application/raml+yaml", () -> renderReplacedContent(ctx, content))
                .html(() -> renderHtml(ctx, path, content))
                .noMatch("application/raml+yaml"));
    } else {
        ctx.byContent(byContentSpec -> byContentSpec.noMatch(() -> ctx.render(ctx.file("api-raml/" + path))));
    }
}
 
开发者ID:vrapio,项目名称:vrap,代码行数:25,代码来源:RamlFilesHandler.java

示例7: generate

import java.nio.file.Path; //导入方法依赖的package包/类
private void generate(BufferedReader reader) throws IOException {
    // array is needed to change value inside a lambda
    long[] count = {0L};
    String root = Utils.TEST_SRC;
    Path testFile = Paths.get(root)
                         .resolve(group.groupName)
                         .resolve("Test.java");
    File testDir = testFile.getParent().toFile();
    if (!testDir.mkdirs() && !testDir.exists()) {
        throw new Error("Can not create directories for "
                        + testFile.toString());
    }

    try (PrintStream ps = new PrintStream(testFile.toFile())) {
        ps.print(COPYRIGHT);
        ps.printf("/* DO NOT MODIFY THIS FILE. GENERATED BY %s */\n",
                  getClass().getName());

        reader.lines()
              .filter(group.filter)
              .forEach(s -> {
                  count[0]++;
                  ps.printf(DESC_FORMAT, s);
              });
        ps.print('\n');
    }
    System.out.printf("%d tests generated in %s%n",
            count[0], group.groupName);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:TestGenerator.java

示例8: scanFile

import java.nio.file.Path; //导入方法依赖的package包/类
public void scanFile(File file) throws IOException {

        FileProcessor fileProcessor = fileProcessorFactory.create(file);

        Path filePath = Paths.get(workingDirectory, file.getName());

        if (!Files.exists(filePath)) {
            return;
        }
        activityStaler.waitToDoActivity();

        String mode = isWrite ? "rw" : "r";
        try (
                RandomAccessFile randomAccessFile = new RandomAccessFile(filePath.toFile(), mode)
        ) {
            fileProcessor.doBeforeFileRead(randomAccessFile);

            while (fileProcessor.hasNextBatchArea()) {
                BatchArea batchArea = fileProcessor.nextBatchArea();

                if (batchArea.isSkip) {
                    continue;
                }

                fileProcessor.doBeforeBatchByteRead();

                byte[] buffer = new byte[(int) batchArea.size];
                randomAccessFile.seek(batchArea.offset);
                randomAccessFile.readFully(buffer);
                fileProcessor.process(buffer, batchArea);

                activityStaler.waitToDoActivity();
            }
        }
    }
 
开发者ID:gaganis,项目名称:odoxSync,代码行数:36,代码来源:FileScanner.java

示例9: validate

import java.nio.file.Path; //导入方法依赖的package包/类
public List<ValidationMessage> validate(Path filepath,
    String validationLevel, int maxErrors) throws IllegalStateException, IOException {
    MZTabFileParser parser = new MZTabFileParser(filepath.toFile(),
        System.out, MZTabErrorType.findLevel(validationLevel), maxErrors);
    MZTabErrorList errorList = parser.getErrorList();
    List<ValidationMessage> validationResults = new ArrayList<>(errorList.
        size());
    for (MZTabError error : errorList.getErrorList()) {
        ValidationMessage.MessageTypeEnum level = ValidationMessage.MessageTypeEnum.INFO;
        switch (error.getType().
            getLevel()) {
            case Error:
                level = ValidationMessage.MessageTypeEnum.ERROR;
                break;
            case Info:
                level = ValidationMessage.MessageTypeEnum.INFO;
                break;
            case Warn:
                level = ValidationMessage.MessageTypeEnum.WARN;
                break;
            default:
                throw new IllegalStateException("State " + error.getType().
                    getLevel() + " is not handled in switch/case statement!");
        }
        ValidationMessage vr = new ValidationMessage().lineNumber(Long.
            valueOf(error.getLineNumber())).
            messageType(level).
            message(error.getMessage()).
            code(error.toString());
        Logger.getLogger(MzTabValidationService.class.getName()).
            info(vr.toString());
        validationResults.add(vr);
    }
    return validationResults;
}
 
开发者ID:nilshoffmann,项目名称:jmzTab-m,代码行数:36,代码来源:EbiValidator.java

示例10: buildOfflineShellFile

import java.nio.file.Path; //导入方法依赖的package包/类
public static File buildOfflineShellFile(IJavaProject jproject, IFile graphModel, String pathGenerator,
		String startElement) throws CoreException, IOException {
	IRuntimeClasspathEntry e = JavaRuntime.computeJREEntry(jproject);
	IVMInstall intall = JavaRuntime.getVMInstall(e.getPath());

	StringBuilder sb = new StringBuilder();
	File javaLocation = intall.getInstallLocation();

	sb.append(javaLocation.getAbsolutePath()).append(File.separator).append("bin").append(File.separator)
			.append("java").append(" -cp ").append("\"");

	String cpSeparator = "";
	String[] classpath = JavaRuntime.computeDefaultRuntimeClassPath(jproject);
	for (String cpElement : classpath) {
		sb.append(cpSeparator).append(cpElement);
		cpSeparator = System.getProperty("path.separator");
	}

	sb.append("\"").append(" org.graphwalker.cli.CLI ").append(" offline ").append(" -m ")
			.append(ResourceManager.toFile(graphModel.getFullPath()).getAbsolutePath()).append(" \"")
			.append(pathGenerator).append("\" ").append(" -e ").append(startElement).append(" --verbose ");

	 
	String extension = isWindows() ? "bat" : "sh";

	Path path = Files.createTempFile("offlineShellRunner", "." + extension);

	Files.write(path, sb.toString().getBytes(StandardCharsets.UTF_8));

	File file = path.toFile();
	 
	ResourceManager.logInfo(jproject.getProject().getName(), "Shell file : " + file.getAbsolutePath());
	return file;
}
 
开发者ID:gw4e,项目名称:gw4e.project,代码行数:35,代码来源:ProcessFacade.java

示例11: watchLogFile

import java.nio.file.Path; //导入方法依赖的package包/类
private Boolean watchLogFile()
    throws IOException, InterruptedException
{
    final Path logPath = LogHelper.getLogPath();
    while ( !Files.exists( logPath ) )
    {
        if ( stopSignal.await( 500, TimeUnit.MILLISECONDS ) )
        {
            System.out.println( "Stopped listener" );
            return false;
        }
    }

    try (final RandomAccessFile raf = new RandomAccessFile( logPath.toFile(), "r" ))
    {
        long currentPosition = initialPosition;
        while ( true )
        {
            if ( stopSignal.await( 200, TimeUnit.MILLISECONDS ) )
            {
                System.out.println( "Stopped listener" );
                return false;
            }
            final long currentLength = raf.length();
            if ( currentLength != currentPosition )
            {
                sendNextLines();
                currentPosition = currentLength;
            }
        }
    }
}
 
开发者ID:aro,项目名称:app-logbrowser,代码行数:33,代码来源:LogTailHandler.java

示例12: fromTemplate

import java.nio.file.Path; //导入方法依赖的package包/类
private static Path fromTemplate(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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:34,代码来源:ContentHandlersTest.java

示例13: saveZipStreamToDirectory

import java.nio.file.Path; //导入方法依赖的package包/类
public File saveZipStreamToDirectory(String entryName, long maxZipEntrySize) throws IOException {
    Path path = StreamUtil.getTempDirectory(entryName);
    File dir = path.toFile();
    LOGGER.debug(MessageFormat.format(Messages.SAVING_INPUT_STREAM_TO_TMP_DIR, dir.getPath()));
    saveEntriesToTempDirectory(path, entryName, maxZipEntrySize);
    LOGGER.debug(MessageFormat.format(Messages.INPUT_STREAM_SAVED_TO_TMP_DIR, dir.getPath()));
    return dir;
}
 
开发者ID:SAP,项目名称:cf-mta-deploy-service,代码行数:9,代码来源:StreamManager.java

示例14: prepareDirectory

import java.nio.file.Path; //导入方法依赖的package包/类
/**
 * Prepare the directory to host the column store.
 */
protected Path prepareDirectory(String dataset, int table, RelationalInput input) {
    String tableName = makeFileName(input.relationName());
    Path dir = Paths.get(DIRECTORY, dataset, tableName);
    logger.info("writing table {} to {}", table, dir.toAbsolutePath());
    try {
        Files.createDirectories(dir);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    this.sampleFile = new File(dir.toFile(), "" + table + "-sample.csv");

    return dir;
}
 
开发者ID:HPI-Information-Systems,项目名称:metanome-algorithms,代码行数:18,代码来源:AbstractColumnStore.java

示例15: parseToJson

import java.nio.file.Path; //导入方法依赖的package包/类
public static String parseToJson(Path path){

        GCLogAnalyzer analyzer = new GCLogAnalyzer(path);
        File f = path.toFile();
        try(InputStream is = new FileInputStream(f)){
           analyzer.parseFile(is);
        }catch (Throwable e){
            logger.warn("parse gclog "+path+" failed!",e);
        }

        return analyzer.logJsonBuilder.toString();
    }
 
开发者ID:ctripcorp,项目名称:cornerstone,代码行数:13,代码来源:GCLogAnalyzer.java


注:本文中的java.nio.file.Path.toFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。