java.nio.file.Paths#get ( )源码实例Demo

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

源代码1 项目: ofdrw   文件: DrawContextTest.java
@Test
void fillRect() throws IOException {
    Path outP = Paths.get("target/Canvas-fillRect.ofd");
    try (OFDDoc ofdDoc = new OFDDoc(outP)) {
        VirtualPage vPage = new VirtualPage(ofdDoc.getPageLayout());

        Canvas canvas = new Canvas(200d, 200d);
        canvas.setPosition(Position.Absolute)
                .setX(5d).setY(45d)
                .setBorder(1d);

        canvas.setDrawer(ctx -> {
            ctx.fillRect(20, 20, 150, 100);
        });
        vPage.add(canvas);

        ofdDoc.addVPage(vPage);
    }
    System.out.println("生成文档位置:" + outP.toAbsolutePath().toString());
}
 
源代码2 项目: Explvs-AIO   文件: ResourceManager.java
private static synchronized boolean saveFileToDataDirectory(final InputStream inputStream, final String relativeFilePath) {
    if (inputStream == null) {
        return false;
    }

    Path outputFilePath = Paths.get(DIRECTORY, relativeFilePath);
    File parentDir = outputFilePath.getParent().toFile();

    if (!parentDir.exists()) {
        if (!parentDir.mkdirs()) {
            System.out.println("Failed to make directory: " + parentDir.toString());
            return false;
        }
    }

    try {
        Files.copy(
                inputStream,
                Paths.get(DIRECTORY, relativeFilePath),
                StandardCopyOption.REPLACE_EXISTING
        );
    } catch (IOException e) {
        e.printStackTrace();
    }
    return true;
}
 
源代码3 项目: dragonwell8_jdk   文件: JDKToolFinder.java
private static String getTool(String tool, String property) throws FileNotFoundException {
    String jdkPath = System.getProperty(property);

    if (jdkPath == null) {
        throw new RuntimeException(
                "System property '" + property + "' not set. This property is normally set by jtreg. "
                + "When running test separately, set this property using '-D" + property + "=/path/to/jdk'.");
    }

    Path toolName = Paths.get("bin", tool + (Platform.isWindows() ? ".exe" : ""));

    Path jdkTool = Paths.get(jdkPath, toolName.toString());
    if (!jdkTool.toFile().exists()) {
        throw new FileNotFoundException("Could not find file " + jdkTool.toAbsolutePath());
    }

    return jdkTool.toAbsolutePath().toString();
}
 
源代码4 项目: sofa-jraft   文件: MemoryKVStoreSnapshotFile.java
<T> void writeToFile(final String rootPath, final String fileName, final Persistence<T> persist) throws Exception {
    final Path path = Paths.get(rootPath, fileName);
    try (final FileOutputStream out = new FileOutputStream(path.toFile());
            final BufferedOutputStream bufOutput = new BufferedOutputStream(out)) {
        final byte[] bytes = this.serializer.writeObject(persist);
        final byte[] lenBytes = new byte[4];
        Bits.putInt(lenBytes, 0, bytes.length);
        bufOutput.write(lenBytes);
        bufOutput.write(bytes);
        bufOutput.flush();
        out.getFD().sync();
    }
}
 
源代码5 项目: size-analyzer   文件: SystemFileDataTest.java
@Test
public void getsCorrectSize() throws Exception {
  File file = TestUtils.getTestDataFile(PATH);
  SystemFileData systemFileData = new SystemFileData(file, Paths.get("foobar.txt"));

  assertThat(systemFileData.getSize()).isEqualTo(1408431L);
}
 
源代码6 项目: Hacktoberfest2019   文件: KerberosMiniKdc.java
private static String prepareWorkDir() throws IOException {
    Path dir = Paths.get(KRB_WORK_DIR);
    File directory = dir.normalize().toFile();

    FileUtils.deleteQuietly(directory);
    FileUtils.forceMkdir(directory);
    return dir.toString();
}
 
源代码7 项目: besu   文件: DatabaseMigrationAcceptanceTest.java
@Before
public void setUp() throws Exception {
  final URL rootURL = DatabaseMigrationAcceptanceTest.class.getResource(dataPath);
  hostDataPath = copyDataDir(rootURL);
  final Path databaseArchive =
      Paths.get(
          DatabaseMigrationAcceptanceTest.class
              .getResource(String.format("%s/besu-db-archive.tar.gz", dataPath))
              .toURI());
  extract(databaseArchive, hostDataPath.toAbsolutePath().toString());
  node = besu.createNode(testName, this::configureNode);
  cluster.start(node);
}
 
public FileSystemProcessInstances(Process<?> process, Path storage, ProcessInstanceMarshaller marshaller) {
    this.process = process;
    this.storage = Paths.get(storage.toString(), process.id());
    this.marshaller = marshaller;

    try {
        Files.createDirectories(this.storage);
    } catch (IOException e) {
        throw new RuntimeException("Unable to create directories for file based storage of process instances", e);
    }
}
 
源代码9 项目: hadoop-ozone   文件: TestDelegationToken.java
@Before
public void init() {
  try {
    conf = new OzoneConfiguration();
    conf.set(OZONE_SCM_CLIENT_ADDRESS_KEY, "localhost");

    conf.setInt(OZONE_SCM_CLIENT_PORT_KEY,
        getPort(OZONE_SCM_CLIENT_PORT_DEFAULT, 100));
    conf.setInt(OZONE_SCM_DATANODE_PORT_KEY,
        getPort(OZONE_SCM_DATANODE_PORT_DEFAULT, 100));
    conf.setInt(OZONE_SCM_BLOCK_CLIENT_PORT_KEY,
        getPort(OZONE_SCM_BLOCK_CLIENT_PORT_DEFAULT, 100));
    conf.setInt(OZONE_SCM_SECURITY_SERVICE_PORT_KEY,
        getPort(OZONE_SCM_SECURITY_SERVICE_PORT_DEFAULT, 100));

    DefaultMetricsSystem.setMiniClusterMode(true);
    final String path = folder.newFolder().toString();
    Path metaDirPath = Paths.get(path, "om-meta");
    conf.set(OZONE_METADATA_DIRS, metaDirPath.toString());
    conf.setBoolean(OZONE_SECURITY_ENABLED_KEY, true);
    conf.set(HADOOP_SECURITY_AUTHENTICATION, KERBEROS.name());

    workDir = GenericTestUtils.getTestDir(getClass().getSimpleName());

    startMiniKdc();
    setSecureConfig();
    createCredentialsInKDC();
    generateKeyPair();
    //      OzoneManager.setTestSecureOmFlag(true);
  } catch (Exception e) {
    LOG.error("Failed to initialize TestSecureOzoneCluster", e);
  }
}
 
private static boolean fileContainsString(String filename, String text) throws IOException {
    Path p = Paths.get(filename);
    for (String line : Files.readAllLines(p, Charset.defaultCharset())) {
        if (line.contains(text)) {
            return true;
        }
    }
    return false;
}
 
源代码11 项目: dragondance   文件: DragonHelper.java
public static boolean runScript(String scriptName, String[] scriptArguments, GhidraState scriptState)
		throws Exception {
	
	//set dummy printwriter to satisfy ghidra scripting api
	
	StringWriter sw = new StringWriter();
	PrintWriter writer = new PrintWriter(sw);
	
	TaskMonitor monitor = new DummyCancellableTaskMonitor();
	
	Path p = Paths.get(
			System.getProperty("user.dir"),
			"Ghidra",
			"Extensions",
			"dragondance",
			"ghidra_scripts",
			scriptName
			);
	
	
	//List<ResourceFile> dirs = GhidraScriptUtil.getScriptSourceDirectories();
	
	ResourceFile scriptSource = new ResourceFile(p.toAbsolutePath().toString());
	
	
	if (scriptSource.exists()) {
		GhidraScriptProvider gsp = GhidraScriptUtil.getProvider(scriptSource);

		if (gsp == null) {
			writer.close();
			throw new IOException("Attempting to run subscript '" + scriptName +
				"': unable to run this script type.");
		}
		
		GhidraScript script = gsp.getScriptInstance(scriptSource, writer);
		script.setScriptArgs(scriptArguments);
		
		script.execute(scriptState, monitor, writer);

	}
	else
	{
		return false;
	}
	
	return true;
}
 
源代码12 项目: TencentKona-8   文件: Shell.java
/**
 * Preprocess the command line arguments passed in by the shell. This method checks, for the first non-option
 * argument, whether the file denoted by it begins with a shebang line. If so, it is assumed that execution in
 * shebang mode is intended. The consequence of this is that the identified script file will be treated as the
 * <em>only</em> script file, and all subsequent arguments will be regarded as arguments to the script.
 * <p>
 * This method canonicalizes the command line arguments to the form {@code <options> <script> -- <arguments>} if a
 * shebang script is identified. On platforms that pass shebang arguments as single strings, the shebang arguments
 * will be broken down into single arguments; whitespace is used as separator.
 * <p>
 * Shebang mode is entered regardless of whether the script is actually run directly from the shell, or indirectly
 * via the {@code jjs} executable. It is the user's / script author's responsibility to ensure that the arguments
 * given on the shebang line do not lead to a malformed argument sequence. In particular, the shebang arguments
 * should not contain any whitespace for purposes other than separating arguments, as the different platforms deal
 * with whitespace in different and incompatible ways.
 * <p>
 * @implNote Example:<ul>
 * <li>Shebang line in {@code script.js}: {@code #!/path/to/jjs --language=es6}</li>
 * <li>Command line: {@code ./script.js arg2}</li>
 * <li>{@code args} array passed to Nashorn: {@code --language=es6,./script.js,arg}</li>
 * <li>Required canonicalized arguments array: {@code --language=es6,./script.js,--,arg2}</li>
 * </ul>
 *
 * @param args the command line arguments as passed into Nashorn.
 * @return the passed and possibly canonicalized argument list
 */
private static String[] preprocessArgs(final String[] args) {
    if (args.length == 0) {
        return args;
    }

    final List<String> processedArgs = new ArrayList<>();
    processedArgs.addAll(Arrays.asList(args));

    // Nashorn supports passing multiple shebang arguments. On platforms that pass anything following the
    // shebang interpreter notice as one argument, the first element of the argument array needs to be special-cased
    // as it might actually contain several arguments. Mac OS X splits shebang arguments, other platforms don't.
    // This special handling is also only necessary if the first argument actually starts with an option.
    if (args[0].startsWith("-") && !System.getProperty("os.name", "generic").startsWith("Mac OS X")) {
        processedArgs.addAll(0, ScriptingFunctions.tokenizeString(processedArgs.remove(0)));
    }

    int shebangFilePos = -1; // -1 signifies "none found"
    // identify a shebang file and its position in the arguments array (if any)
    for (int i = 0; i < processedArgs.size(); ++i) {
        final String a = processedArgs.get(i);
        if (!a.startsWith("-")) {
            final Path p = Paths.get(a);
            String l = "";
            try (final BufferedReader r = Files.newBufferedReader(p)) {
                l = r.readLine();
            } catch (IOException ioe) {
                // ignore
            }
            if (l.startsWith("#!")) {
                shebangFilePos = i;
            }
            // We're only checking the first non-option argument. If it's not a shebang file, we're in normal
            // execution mode.
            break;
        }
    }
    if (shebangFilePos != -1) {
        // Insert the argument separator after the shebang script file.
        processedArgs.add(shebangFilePos + 1, "--");
    }
    return processedArgs.toArray(new String[0]);
}
 
源代码13 项目: netcdf-java   文件: GribCdmIndex.java
/**
 * Update Grib Collection if needed
 *
 * @return true if the collection was updated
 */
public static boolean updateGribCollection(FeatureCollectionConfig config, CollectionUpdateType updateType,
    Logger logger) throws IOException {
  if (logger == null)
    logger = classLogger;

  long start = System.currentTimeMillis();

  Formatter errlog = new Formatter();
  CollectionSpecParser specp = config.getCollectionSpecParser(errlog);
  Path rootPath = Paths.get(specp.getRootDir());
  boolean isGrib1 = config.type == FeatureCollectionType.GRIB1;

  boolean changed;

  if (config.ptype == FeatureCollectionConfig.PartitionType.none
      || config.ptype == FeatureCollectionConfig.PartitionType.all) {

    try (CollectionAbstract dcm = new CollectionPathMatcher(config, specp, logger)) {
      changed =
          updateGribCollection(isGrib1, dcm, updateType, FeatureCollectionConfig.PartitionType.none, logger, errlog);
    }

  } else if (config.ptype == FeatureCollectionConfig.PartitionType.timePeriod) {

    try (TimePartition tp = new TimePartition(config, specp, logger)) {
      changed = updateTimePartition(isGrib1, tp, updateType, logger);
    }

  } else {

    // LOOK assume wantSubdirs makes it into a Partition. Isnt there something better ??
    if (specp.wantSubdirs()) { // its a partition

      try (DirectoryPartition dpart =
          new DirectoryPartition(config, rootPath, true, new GribCdmIndex(logger), NCX_SUFFIX, logger)) {
        dpart.putAuxInfo(FeatureCollectionConfig.AUX_CONFIG, config);
        changed = updateDirectoryCollectionRecurse(isGrib1, dpart, config, updateType, logger);
      }

    } else { // otherwise its a leaf directory
      changed = updateLeafCollection(isGrib1, config, updateType, true, logger, rootPath);
    }
  }

  long took = System.currentTimeMillis() - start;
  logger.info("updateGribCollection {} changed {} took {} msecs", config.collectionName, changed, took);
  return changed;
}
 
源代码14 项目: besu   文件: BlocksSubCommand.java
private void checkCommand(
    final ExportSubCommand exportSubCommand, final Long startBlock, final Long endBlock) {
  checkNotNull(exportSubCommand.parentCommand);

  final Optional<Long> maybeStartBlock = getStartBlock();
  final Optional<Long> maybeEndBlock = getEndBlock();

  maybeStartBlock
      .filter(blockNum -> blockNum < 0)
      .ifPresent(
          (blockNum) -> {
            throw new CommandLine.ParameterException(
                spec.commandLine(),
                "Parameter --start-block ("
                    + blockNum
                    + ") must be greater than or equal to zero.");
          });

  maybeEndBlock
      .filter(blockNum -> blockNum < 0)
      .ifPresent(
          (blockNum) -> {
            throw new CommandLine.ParameterException(
                spec.commandLine(),
                "Parameter --end-block ("
                    + blockNum
                    + ") must be greater than or equal to zero.");
          });

  if (maybeStartBlock.isPresent() && maybeEndBlock.isPresent()) {
    if (endBlock <= startBlock) {
      throw new CommandLine.ParameterException(
          spec.commandLine(),
          "Parameter --end-block ("
              + endBlock
              + ") must be greater start block ("
              + startBlock
              + ").");
    }
  }

  // Error if data directory is empty
  final Path databasePath =
      Paths.get(
          parentCommand.parentCommand.dataDir().toAbsolutePath().toString(),
          BesuController.DATABASE_PATH);
  final File databaseDirectory = new File(databasePath.toString());
  if (!databaseDirectory.isDirectory() || databaseDirectory.list().length == 0) {
    // Empty data directory, nothing to export
    throw new CommandLine.ParameterException(
        spec.commandLine(),
        "Chain is empty.  Unable to export blocks from specified data directory: "
            + databaseDirectory.toString());
  }
}
 
源代码15 项目: hadoop-ozone   文件: GenesisUtil.java
public static Path getTempPath() {
  return Paths.get(System.getProperty(TMP_DIR));
}
 
源代码16 项目: chart-fx   文件: WriteDataSetToFileSample.java
@Override
public void start(final Stage primaryStage) {
    final String userHome = System.getProperty("user.home");

    final XYChart chart1 = new XYChart(new DefaultNumericAxis(), new DefaultNumericAxis());
    final XYChart chart2 = new XYChart();

    now = System.currentTimeMillis();
    dataSet1 = getDemoDataSet(now, true);
    dataSet2 = getDemoDataSet(now, false);
    dataSet2.getMetaInfo().put("magNr", Integer.toString(5));
    chart1.getDatasets().setAll(dataSet1, dataSet2); // two data sets

    final Scene scene = new Scene(chart1, 800, 600);
    primaryStage.setTitle(this.getClass().getSimpleName() + " - original");
    primaryStage.setScene(scene);
    primaryStage.setOnCloseRequest(evt -> Platform.exit());

    final Stage secondaryStage = new Stage();

    secondaryStage.setTitle(this.getClass().getSimpleName() + " - recovered");
    secondaryStage.setScene(new Scene(chart2, 800, 600));
    secondaryStage.setOnCloseRequest(evt -> Platform.exit());
    primaryStage.show();
    secondaryStage.show();

    LOGGER.atInfo().log("userHome = " + userHome);
    final Path path = Paths.get(userHome + "/ChartSamples");
    final String fileName = PNG_FILE_NAME;

    final boolean addDateTimeToFileName = true;

    // write DataSet to File and recover
    DataSetUtils.writeDataSetToFile(dataSet1, path, CSV_FILE_NAME_1, false);
    DataSetUtils.writeDataSetToFile(dataSet2, path, CSV_FILE_NAME_2, true);
    DataSetUtils.writeDataSetToFile(dataSet2, path, CSV_FILE_NAME_SYSTEMTIME, false);

    // start periodic screen capture
    final PeriodicScreenCapture screenCapture = new PeriodicScreenCapture(path, fileName, scene, DEFAULT_DELAY,
            DEFAULT_PERIOD, addDateTimeToFileName);

    screenCapture.addListener(obs -> {
        final long userTimeStampMillis = System.currentTimeMillis();

        // add some important meta data to dataSet1 (e.g. acquisition time
        // stamp)
        dataSet1.getMetaInfo().put("acqTimeStamp", Long.toString(userTimeStampMillis));
        dataSet2.getMetaInfo().put("acqTimeStamp", Long.toString(userTimeStampMillis));

        final String actualFileName1 = DataSetUtils.writeDataSetToFile(dataSet1, path, CSV_FILE_NAME_1_TIMESTAMED,
                false);
        final String actualFileName2 = DataSetUtils.writeDataSetToFile(dataSet2, path, CSV_FILE_NAME_2_TIMESTAMED,
                true);

        // to suppress serialising the meta-data, default: true
        // DataSetSerialiser.setMetaDataSerialised(false); // uncomment
        // to suppress serialising data labels and styles, default: true
        // DataSetSerialiser.setDataLablesSerialised(false); // uncomment
        boolean asFloat = true;
        fastByteBuffer.reset(); // '0' writing at start of buffer
        DataSetSerialiser.writeDataSetToByteArray(dataSet2, fastByteBuffer, asFloat);
        LOGGER.atInfo().log("written bytes to byte buffer = " + fastByteBuffer.position());
        fastByteBuffer.reset(); // return read position to '0'

        LOGGER.atInfo().log("write data time-stamped to directory = " + path);
        LOGGER.atInfo().log("actualFileName1 = " + actualFileName1);
        LOGGER.atInfo().log("actualFileName2 = " + actualFileName2);

        // recover written data sets
        final DataSet recoveredDataSet1 = DataSetUtils.readDataSetFromFile(actualFileName1);
        final DataSet recoveredDataSet2 = DataSetUtils.readDataSetFromFile(actualFileName2);
        final DataSet recoveredDataSet3 = DataSetSerialiser.readDataSetFromByteArray(fastByteBuffer);

        chart2.getDatasets().clear();
        if (recoveredDataSet1 != null) {
            chart2.getDatasets().add(recoveredDataSet1);
        }

        if (recoveredDataSet2 != null) {
            chart2.getDatasets().add(recoveredDataSet2);
        }

        if (recoveredDataSet3 != null) {
            chart2.getDatasets().add(recoveredDataSet3);
        }

        // generate new data sets
        now = System.currentTimeMillis();
        dataSet1 = getDemoDataSet(now, true);
        dataSet2 = getDemoDataSet(now, false);
        chart1.getDatasets().setAll(dataSet1, dataSet2); // two data sets
    });

    screenCapture.start();

    // screenCapture.stop();
}
 
源代码17 项目: TencentKona-8   文件: TestJcmdDumpLimited.java
private static void testDumpEndBegin() throws Exception {
    Path testEndBegin = Paths.get("testEndBegin.jfr");
    OutputAnalyzer output = JcmdHelper.jcmd("JFR.dump", "filename=" + testEndBegin.toFile().getAbsolutePath(), "begin=" + Instant.now(), "end=" + Instant.now().minusSeconds(200));
    output.shouldContain("Dump failed, begin must preceed end.");
    assertMissingFile(testEndBegin);
}
 
public DirectoryReportDelivery(String directoryPath) {
    super("File-based report delivery");
    this.dir = Paths.get(directoryPath);
}
 
源代码19 项目: size-analyzer   文件: ProjectAnalyzer.java
private static ImmutableList<Suggestion> analyzeDirectory(
    File rootDirectory,
    Project project,
    File directory,
    ImmutableList<ProjectSuggester> projectSuggesters,
    ImmutableList<ProjectTreeSuggester> suggesters) {
  ImmutableList.Builder<Suggestion> resultBuilder = ImmutableList.<Suggestion>builder();
  File[] files = directory.listFiles();
  for (File file : files) {
    String name = file.getName();
    if (name.equals(".gradle") || name.equals(".idea") || name.equals("build")) {
      continue;
    }
    if (file.isDirectory()) {
      File buildFile = new File(file, Project.BUILD_GRADLE);
      if (buildFile.exists()) {
        Project subProject = Project.create(file, project);
        resultBuilder.addAll(
            analyzeProject(rootDirectory, subProject, file, projectSuggesters, suggesters));
      } else {
        // recurse, through directory under the same directory.
        resultBuilder.addAll(
            analyzeDirectory(rootDirectory, project, file, projectSuggesters, suggesters));
      }
    } else {
      GradleContext context =
          project != null ? project.getContext() : GradleContext.create(1, false);
      Path pathWithinModule =
          project != null
              ? Paths.get(project.getProjectDirectory().getPath())
                  .relativize(Paths.get(file.getPath()))
              : Paths.get(file.getName());
      Path pathWithinRoot =
          Paths.get(rootDirectory.getPath()).relativize(Paths.get(file.getPath()));
      for (ProjectTreeSuggester suggester : suggesters) {
        SystemFileData systemFileData =
            new SystemFileData(file, pathWithinRoot, pathWithinModule);
        resultBuilder.addAll(suggester.processProjectEntry(context, systemFileData));
      }
    }
  }

  return resultBuilder.build();
}
 
源代码20 项目: Java-Coding-Problems   文件: Main.java
public static void main(String[] args) throws IOException, InterruptedException {

        final Path path = Paths.get("D:/captures");
        VideoCaptureWatcher watcher = new VideoCaptureWatcher();

        watcher.watchVideoCaptureSystem(path);
    }
 
 方法所在类
 同类方法