本文整理汇总了Java中java.nio.file.Paths类的典型用法代码示例。如果您正苦于以下问题:Java Paths类的具体用法?Java Paths怎么用?Java Paths使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Paths类属于java.nio.file包,在下文中一共展示了Paths类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: initZipLogFile
import java.nio.file.Paths; //导入依赖的package包/类
private void initZipLogFile(final Cmd cmd) throws IOException {
// init log directory
try {
Files.createDirectories(DEFAULT_LOG_PATH);
} catch (FileAlreadyExistsException ignore) {
LOGGER.warn("Log path %s already exist", DEFAULT_LOG_PATH);
}
// init zipped log file for tmp
Path stdoutPath = Paths.get(DEFAULT_LOG_PATH.toString(), getLogFileName(cmd, Log.Type.STDOUT, true));
Files.deleteIfExists(stdoutPath);
stdoutLogPath = Files.createFile(stdoutPath);
// init zip stream for stdout log
stdoutLogStream = new FileOutputStream(stdoutLogPath.toFile());
stdoutLogZipStream = new ZipOutputStream(stdoutLogStream);
ZipEntry outEntry = new ZipEntry(cmd.getId() + ".out");
stdoutLogZipStream.putNextEntry(outEntry);
}
示例2: SimpleFileDataManager
import java.nio.file.Paths; //导入依赖的package包/类
@SneakyThrows
public SimpleFileDataManager(String file) {
this.path = Paths.get(file);
if (!this.path.toFile().exists()) {
log.info("Could not find config file at " + this.path.toFile().getAbsolutePath() + ", creating a new one...");
if (this.path.toFile().createNewFile()) {
log.info("Generated new config file at " + this.path.toFile().getAbsolutePath() + ".");
FileIOUtils.write(this.path, this.data.stream().collect(Collectors.joining()));
log.info("Please, fill the file with valid properties.");
} else {
log.warn("Could not create config file at " + file);
}
}
Collections.addAll(data, NEWLINE_PATTERN.split(FileIOUtils.read(this.path)));
data.removeIf(s -> s.startsWith("//"));
}
示例3: acceptsAndRenders
import java.nio.file.Paths; //导入依赖的package包/类
@Test
public void acceptsAndRenders() throws Exception {
final Path output = Files.createTempDirectory("").resolve("x2");
final Path input = Paths.get(".");
new App(input, output).analyze();
final Results results = new Results();
results.add("org.takes:takes", output);
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new Xembler(
new Directives().add("repos").append(
new Joined<Directive>(results.recent())
)
).xmlQuietly()
),
XhtmlMatchers.hasXPath("/repos")
);
}
示例4: saveConfig
import java.nio.file.Paths; //导入依赖的package包/类
/**
* Saves these options to disk, with the given file name.
* @param name The name to save as.
* @return True if the save was successful, false if there was an error.
*/
public boolean saveConfig(String name) {
File saveFile = Paths.get(BASE_CONFIG_STRING + name).toFile();
saveFile.getParentFile().mkdirs();
try {
saveFile.createNewFile();
FileOutputStream writeTo = new FileOutputStream(saveFile);
this.store(writeTo, "");
writeTo.close();
return true;
} catch (IOException e) {
Logging.log(ERROR_SAVING_MSG, LogMessageType.ERROR);
Logging.log(e);
}
return false;
}
示例5: DefaultIRIConverterPortuguese
import java.nio.file.Paths; //导入依赖的package包/类
public DefaultIRIConverterPortuguese(QueryExecutionFactory qef, String cacheDirectory) {
this.qef = qef;
// use tmp as default cache directory
if (cacheDirectory == null) {
cacheDirectory = System.getProperty("java.io.tmpdir") + "/triple2nl/cache/portuguese";
}
cacheDirectory += "/dereferenced";
try {
Files.createDirectories(Paths.get(cacheDirectory));
} catch (IOException e) {
logger.error("Creation of folder + " + cacheDirectory + " failed.", e);
}
logger.debug("Using folder " + cacheDirectory + " as cache for IRI converter.");
uriDereferencer = new URIDereferencer(new File(cacheDirectory));
}
示例6: extractReadFromStdin
import java.nio.file.Paths; //导入依赖的package包/类
@Test
public void extractReadFromStdin() throws IOException {
Path path = Paths.get("extract");
Path jarPath = path.resolve("extractReadFromStdin.jar"); // for extracting
createJar(jarPath, RES1);
for (String opts : new String[]{"x" ,"-x", "--extract"}) {
if (legacyOnly && opts.startsWith("--"))
continue;
jarWithStdinAndWorkingDir(jarPath.toFile(), path.toFile(), opts)
.assertSuccess()
.resultChecker(r ->
assertTrue(Files.exists(path.resolve(RES1)),
"Expected to find:" + path.resolve(RES1))
);
FileUtils.deleteFileIfExistsWithRetry(path.resolve(RES1));
}
FileUtils.deleteFileTreeWithRetry(path);
}
示例7: getAllPullRequests_should_return_all_pull_requests_as_list
import java.nio.file.Paths; //导入依赖的package包/类
@Test
public void getAllPullRequests_should_return_all_pull_requests_as_list() throws Exception {
final Repository repo = mock( Repository.class );
final String json = new String( Files.readAllBytes(
Paths.get( "src/test/resources/org/retest/rebazer/service/bitbucketservicetest/response.json" ) ) );
final DocumentContext documentContext = JsonPath.parse( json );
when( config.getTeam() ).thenReturn( "test_team" );
when( repo.getName() ).thenReturn( "test_repo_name" );
when( bitbucketTemplate.getForObject( anyString(), eq( String.class ) ) ).thenReturn( json );
final int expectedId = (int) documentContext.read( "$.values[0].id" );
final String expectedUrl =
"/repositories/" + config.getTeam() + "/" + repo.getName() + "/pullrequests/" + expectedId;
final List<PullRequest> expected = Arrays.asList( PullRequest.builder().id( expectedId ).repo( repo.getName() )
.source( documentContext.read( "$.values[0].source.branch.name" ) )
.destination( documentContext.read( "$.values[0].destination.branch.name" ) ).url( expectedUrl )
.lastUpdate( documentContext.read( "$.values[0].updated_on" ) ).build() );
final List<PullRequest> actual = cut.getAllPullRequests( repo );
assertThat( actual ).isEqualTo( expected );
}
示例8: issue9_library
import java.nio.file.Paths; //导入依赖的package包/类
@Test
@Ignore("works with solc version > 0.4.18")
public void issue9_library() throws Exception {
File pom = new File(resources.getBasedir("issue"), "issue9.pom.xml");
assertNotNull(pom);
assertTrue(pom.exists());
JavaClassGeneratorMojo mojo = (JavaClassGeneratorMojo) mojoRule.lookupMojo("generate-sources", pom);
assertNotNull(mojo);
mojo.sourceDestination = testFolder.getRoot().getPath();
mojo.execute();
Path path = Paths.get(mojo.sourceDestination);
List<Path> files = Files.find(path, 99, (p, bfa) -> bfa.isRegularFile()).collect(Collectors.toList());
assertThat("ConvertLib is created", files.size(), is(1));
assertThat(files.get(0).getFileName().toString(), is("ConvertLib.java"));
}
示例9: calculateHash
import java.nio.file.Paths; //导入依赖的package包/类
private void calculateHash(FileInfo file) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA3-256");
messageDigest.update(Files.readAllBytes(Paths.get(file.getPath())));
ByteArrayInputStream inputStream = new ByteArrayInputStream(messageDigest.digest());
String hash = IntStream.generate(inputStream::read)
.limit(inputStream.available())
.mapToObj(i -> Integer.toHexString(i))
.map(s -> ("00" + s).substring(s.length()))
.collect(Collectors.joining());
file.setHash(hash);
} catch (NoSuchAlgorithmException | IOException ex) {
// This algorithm is guaranteed to be there by the JDK, so we'll
// wrap the checked exception in an unchecked exception so that we
// don't have to expose it to consuming classes. This *should* never
// actually run, but it's probably best to be cautious here.
throw new RuntimeException(ex);
}
}
示例10: loadCustomEmitters
import java.nio.file.Paths; //导入依赖的package包/类
private void loadCustomEmitters(String projectPath) {
for (String xmlFile : FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(projectPath), "xml")) {
boolean isEmitter = false;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
if (doc.getDocumentElement().getNodeName().equalsIgnoreCase("emitter")) {
isEmitter = true;
}
} catch (SAXException | IOException | ParserConfigurationException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
if (isEmitter) {
CustomEmitter.load(xmlFile);
}
}
}
示例11: run
import java.nio.file.Paths; //导入依赖的package包/类
void run() throws Exception {
compileTestClass();
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo.class").toUri()), "lambda$bar$0", simpleLambdaExpectedLNT);
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo.class").toUri()), "lambda$variablesInLambdas$1", lambdaWithVarsExpectedLNT);
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo$1FooBar.class").toUri()), "run", insideLambdaWithVarsExpectedLNT);
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo.class").toUri()), "lambda$variablesInLambdas$2", lambdaVoid2VoidExpectedLNT);
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo.class").toUri()), "$deserializeLambda$", deserializeExpectedLNT);
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo.class").toUri()), "lambda$variablesInLambdas$3", lambdaBridgeExpectedLNT);
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo.class").toUri()), "assignLambda", assignmentExpectedLNT);
checkClassFile(new File(Paths.get(System.getProperty("user.dir"),
"Foo.class").toUri()), "callLambda", callExpectedLNT);
}
示例12: testExecuteQueryFilter
import java.nio.file.Paths; //导入依赖的package包/类
@Test
public void testExecuteQueryFilter() throws Exception {
cleanInsert(Paths.get("src/test/resources/data/setup", "testExecuteQuery.ltsv"));
List<String> log = TestAppender.getLogbackLogs(() -> {
SqlContext ctx = agent.contextFrom("example/select_product")
.paramList("product_id", new BigDecimal("0"), new BigDecimal("2"))
.param("_userName", "testUserName").param("_funcId", "testFunction").setSqlId("111");
ctx.setResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);
agent.query(ctx);
});
assertThat(log, is(Files.readAllLines(
Paths.get("src/test/resources/data/expected/AuditLogSqlFilter", "testExecuteQueryFilter.txt"),
StandardCharsets.UTF_8)));
}
示例13: read
import java.nio.file.Paths; //导入依赖的package包/类
public static char[][] read(String filename) {
try {
// Read contents of the file.
return Files.readAllLines(Paths.get(filename))
// Convert to a stream without first line
// Because we don't need row and col count
.stream().skip(1)
// Filter out empty lines.
.filter(line -> line.length() > 0)
// Transform each string to array of chars.
.map(String::toCharArray)
// Collect the arrays into a 2D array.
.toArray(char[][]::new);
} catch (Exception e) {
// Handle file not found, etc.
return null;
}
}
示例14: loadFiles
import java.nio.file.Paths; //导入依赖的package包/类
public void loadFiles(boolean today) {
// This seems backwards, but at 01:00, we want to download today (starting at 04:00)
interestingDates = Arrays.asList(LocalDate.now(), LocalDate.now().plusDays(1));
Log.send(LogCode.PLANNING_STARTED_LOADING, "Started loading");
LOGGER.info("Starting to load calendar files");
handleFiles(Paths.get(Configuration.getKv7CalendarPath()), this::getCalendar);
LOGGER.info("Starting to load planning files");
handleFiles(Paths.get(Configuration.getKv7PlanningPath()), this::getPlanning);
QuayDataProvider.replace(planningRecords);
LineProvider.backup();
DestinationProvider.backup();
TimingPointProvider.backup();
Log.send(LogCode.PLANNING_LOADED, String.format("Loaded %s records for %s and %s", planningRecords.size(), interestingDates.get(0).toString(),
interestingDates.get(1).toString()));
}
示例15: updateReadStdinWriteStdout
import java.nio.file.Paths; //导入依赖的package包/类
@Test
public void updateReadStdinWriteStdout() throws IOException {
Path path = Paths.get("updateReadStdinWriteStdout.jar");
for (String opts : new String[]{"u", "-u", "--update"}) {
if (legacyOnly && opts.startsWith("--"))
continue;
createJar(path, RES1);
jarWithStdin(path.toFile(), opts, RES2)
.assertSuccess()
.resultChecker(r -> {
ASSERT_CONTAINS_RES1.accept(r.stdoutAsStream());
ASSERT_CONTAINS_RES2.accept(r.stdoutAsStream());
ASSERT_CONTAINS_MAINFEST.accept(r.stdoutAsStream());
});
}
FileUtils.deleteFileIfExistsWithRetry(path);
}