本文整理匯總了Java中java.nio.file.FileSystems類的典型用法代碼示例。如果您正苦於以下問題:Java FileSystems類的具體用法?Java FileSystems怎麽用?Java FileSystems使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
FileSystems類屬於java.nio.file包,在下文中一共展示了FileSystems類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: getConfig
import java.nio.file.FileSystems; //導入依賴的package包/類
@Override
public Config getConfig() throws IOException {
PathMatcher pathMatcher;
try {
pathMatcher = FileSystems.getDefault().getPathMatcher(inputFilePattern);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
"Invalid input file pattern: " + inputFilePattern);
}
try (Stream<Path> pathStream = Files.walk(baseDirectory)) {
return pathStream
.filter(p -> Files.isRegularFile(p) && pathMatcher.matches(p))
.map(p -> ConfigFactory.parseFile(p.toFile()))
.reduce(ConfigFactory.empty(), Config::withFallback)
.resolve(
ConfigResolveOptions.defaults()
.setAllowUnresolved(true)
.setUseSystemEnvironment(false)
);
}
}
示例2: create
import java.nio.file.FileSystems; //導入依賴的package包/類
public static Path create( URI uri )
{
try
{
return Paths.get( uri );
}
catch( FileSystemNotFoundException nfe )
{
try
{
Map<String, String> env = new HashMap<>();
env.put( "create", "true" ); // creates zip/jar file if not already exists
FileSystem fs = FileSystems.newFileSystem( uri, env );
return fs.provider().getPath( uri );
}
catch( IOException e )
{
throw new RuntimeException( e );
}
}
}
示例3: toPath
import java.nio.file.FileSystems; //導入依賴的package包/類
/**
* Convert a local URL (file:// or jar:// protocol) to a {@link Path}
* @param resource the URL resource
* @return the Path
* @throws URISyntaxException
* @throws IOException
*/
public static Path toPath(URL resource) throws IOException, URISyntaxException {
if (resource == null) return null;
final String protocol = resource.getProtocol();
if ("file".equals(protocol)) {
return Paths.get(resource.toURI());
} else if ("jar".equals(protocol)) {
final String s = resource.toString();
final int separator = s.indexOf("!/");
final String entryName = s.substring(separator + 2);
final URI fileURI = URI.create(s.substring(0, separator));
final FileSystem fileSystem;
synchronized (jarFileSystems) {
if (jarFileSystems.add(fileURI)) {
fileSystem = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap());
} else {
fileSystem = FileSystems.getFileSystem(fileURI);
}
}
return fileSystem.getPath(entryName);
} else {
throw new IOException("Can't read " + resource + ", unknown protocol '" + protocol + "'");
}
}
示例4: writeSnapshot
import java.nio.file.FileSystems; //導入依賴的package包/類
@Override
public void writeSnapshot(String snapshotDir) {
// 采用軟鏈接形式,提升速度和節省空間
try {
File messageDirFile = new File(messageDir);
File snapshotDirFile = new File(snapshotDir);
if (snapshotDirFile.exists()) {
FileUtils.deleteDirectory(snapshotDirFile);
}
if (messageDirFile.exists()) {
Path link = FileSystems.getDefault().getPath(snapshotDir);
Path target = FileSystems.getDefault().getPath(messageDir).toRealPath();
Files.createSymbolicLink(link, target);
}
} catch (IOException ex) {
LOG.warn("write snapshot failed, exception:", ex);
}
}
示例5: setup
import java.nio.file.FileSystems; //導入依賴的package包/類
@BeforeClass
public void setup() {
theFileSystem = FileSystems.getFileSystem(URI.create("jrt:/"));
Path modulesPath = Paths.get(System.getProperty("java.home"),
"lib", "modules");
isExplodedBuild = Files.notExists(modulesPath);
if (isExplodedBuild) {
System.out.printf("%s doesn't exist.", modulesPath.toString());
System.out.println();
System.out.println("It is most probably an exploded build."
+ " Skip non-default FileSystem testing.");
return;
}
Map<String, String> env = new HashMap<>();
// set java.home property to be underlying java.home
// so that jrt-fs.jar loading is exercised.
env.put("java.home", System.getProperty("java.home"));
try {
fs = FileSystems.newFileSystem(URI.create("jrt:/"), env);
} catch (IOException ioExp) {
throw new RuntimeException(ioExp);
}
}
示例6: Watchdog
import java.nio.file.FileSystems; //導入依賴的package包/類
/**
* Initiates a Watchdog for specific resource. File must be located within
* the resources location of a dev machine or within
* {@code {catalina.home}/properties}
*
*/
public Watchdog(final DynamicLoadable loader, final boolean startImmediately) {
if (loader == null) {
throw new IllegalArgumentException("loader must be set");
}
resource = loader.getResourceFilename();
if (resource == null) {
throw new IllegalArgumentException("resource in loader must be set");
}
autostart = startImmediately;
this.loader = loader;
try {
watchService = FileSystems.getDefault().newWatchService();
final String path = loader.getResourceLocation();
logger.info("Watchdog [" + path + "]");
logger.info("INFO: Watchdog [" + path + resource + "]");
Paths.get(path).register(watchService, ENTRY_MODIFY);
} catch (final IOException e) {
logger.warning(e.getMessage());
}
}
示例7: WatchDir
import java.nio.file.FileSystems; //導入依賴的package包/類
/**
* Creates a WatchService and registers the given directory
*/
WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey, Path>();
this.recursive = recursive;
if (recursive) {
System.out.format("Scanning %s ...\n", dir);
registerAll(dir);
System.out.println("Done.");
} else {
register(dir);
}
// enable trace after initial registration
this.trace = true;
}
示例8: test
import java.nio.file.FileSystems; //導入依賴的package包/類
@Test
public void test() throws Exception {
Path path = FileSystems.getDefault().getPath("", "index");
Directory directory = FSDirectory.open(path);
Analyzer analyzer = new StandardAnalyzer();
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer).setOpenMode(IndexWriterConfig.OpenMode.CREATE);
IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
Document document = new Document();
document.add(new LegacyLongField("id", 5499, Field.Store.YES));
document.add(new Field("title", "小米6", TYPE_STORED));
document.add(new Field("sellPoint", "驍龍835,6G內存,雙攝!", TYPE_STORED));
document.
indexWriter.addDocument(document);
indexWriter.commit();
indexWriter.close();
}
示例9: testNumberSuffixMatches
import java.nio.file.FileSystems; //導入依賴的package包/類
@Test
public void testNumberSuffixMatches() {
final FileSystem fs = FileSystems.getDefault();
final Path baseName = fs.getPath("/tmp", "logfile.log");
final NumberSuffixStrategy m = new NumberSuffixStrategy(baseName);
assertTrue("same file matches", m.pathMatches(fs.getPath("/tmp", "logfile.log")));
assertTrue("number suffix matches", m.pathMatches(fs.getPath("/tmp", "logfile.log.1")));
assertTrue("multi-digit suffix matches", m.pathMatches(fs.getPath("/tmp", "logfile.log.1345345")));
assertFalse("separator must be '.'", m.pathMatches(fs.getPath("/tmp", "logfile.log-123")));
assertFalse("more suffixes don't match", m.pathMatches(fs.getPath("/tmp", "logfile.log.1234.gz")));
assertFalse("wrong base path doesn't match", m.pathMatches(fs.getPath("/var/log", "logfile.log.1234")));
assertTrue("paths are normalized", m.pathMatches(fs.getPath("/tmp/bar/..", "logfile.log.1")));
assertTrue("relative paths are resolved", m.pathMatches(fs.getPath("logfile.log.1")));
}
示例10: loadExtensions
import java.nio.file.FileSystems; //導入依賴的package包/類
private Map<String, Accessible> loadExtensions() {
Map<String, Accessible> accessibleMap = new HashMap<>();
pluginManager = new DefaultPluginManager(
FileSystems.getDefault().getPath(MainVerticle.pluginDir).toAbsolutePath());
pluginManager.loadPlugins();
pluginManager.startPlugins();
List<Accessible> accessibleList = pluginManager.getExtensions(Accessible.class);
for (Accessible accessible : accessibleList) {
String pluginName = accessible.getClass().getDeclaringClass().getName();
logger.info("{} is loaded ...", pluginName);
accessibleMap.put(pluginName, accessible);
}
return accessibleMap;
}
示例11: generate
import java.nio.file.FileSystems; //導入依賴的package包/類
public static void generate() throws IOException {
int stringsPerFile = (1 << 14);
for (int fileNumber = 0; fileNumber < 2; fileNumber++) {
Path path = FileSystems.getDefault().getPath("StringPool" + fileNumber + ".java");
PrintStream out = new PrintStream(
Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND));
out.println(
"// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file");
out.println(
"// for details. All rights reserved. Use of this source code is governed by a");
out.println("// BSD-style license that can be found in the LICENSE file.");
out.println("package jumbostring;");
out.println();
out.println("class StringPool" + fileNumber + " {");
int offset = fileNumber * stringsPerFile;
for (int i = offset; i < offset + stringsPerFile; i++) {
out.println(" public static final String s" + i + " = \"" + i + "\";");
}
out.println("}");
out.close();
}
}
示例12: getFileSystem
import java.nio.file.FileSystems; //導入依賴的package包/類
/**
* Returns a new FileSystem to read REST resources, or null if they
* are available from classpath.
*/
@SuppressForbidden(reason = "proper use of URL, hack around a JDK bug")
protected static FileSystem getFileSystem() throws IOException {
// REST suite handling is currently complicated, with lots of filtering and so on
// For now, to work embedded in a jar, return a ZipFileSystem over the jar contents.
URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true);
if (codeLocation.getFile().endsWith(".jar") && loadPackaged) {
try {
// hack around a bug in the zipfilesystem implementation before java 9,
// its checkWritable was incorrect and it won't work without write permissions.
// if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location.
Path tmp = Files.createTempFile(null, ".jar");
try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) {
Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
}
return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap());
} catch (URISyntaxException e) {
throw new IOException("couldn't open zipfilesystem: ", e);
}
} else {
return null;
}
}
示例13: validate
import java.nio.file.FileSystems; //導入依賴的package包/類
static void validate(Module module) throws IOException {
ModuleDescriptor md = module.getDescriptor();
// read m1/module-info.class
FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"),
Collections.emptyMap());
Path path = fs.getPath("/", "modules", module.getName(), "module-info.class");
ModuleDescriptor md1 = ModuleDescriptor.read(Files.newInputStream(path));
// check the module descriptor of a system module and read from jimage
checkPackages(md.packages(), "p1", "p2");
checkPackages(md1.packages(), "p1", "p2");
try (InputStream in = Files.newInputStream(path)) {
checkModuleTargetAttribute(in, "p1");
}
}
示例14: testNewFileSystem
import java.nio.file.FileSystems; //導入依賴的package包/類
@Test
public void testNewFileSystem() throws IOException {
for (String[] params : new String[][] {
// $uri, $mountPoint
{ "tpath:/", "file:/" },
{ "tpath:///", "file:/" },
{ "tpath:/foo", "file:/" },
{ "tpath:/foo/", "file:/" },
{ "tpath:/foo/bar", "file:/foo/" },
{ "tpath:/foo/bar/", "file:/foo/" },
{ "tpath:/foo/bar.mok/", "mok:file:/foo/bar.mok!/" },
{ "tpath:/foo.mok/bar", "mok:file:/foo.mok!/" },
{ "tpath:/foo.mok/bar.mok", "mok:mok:file:/foo.mok!/bar.mok!/" },
}) {
final URI uri = URI.create(params[0]);
final FsMountPoint mountPoint = FsMountPoint.create(
URI.create(params[1]));
final TFileSystem fs = (TFileSystem) FileSystems.newFileSystem(
uri, getEnvironment(), TFileSystemTest.class.getClassLoader());
fs.close();
assertThat(fs.isOpen(), is(true));
assertThat(fs.getMountPoint(), is(mountPoint));
}
}
示例15: watch
import java.nio.file.FileSystems; //導入依賴的package包/類
/**
* Run the handler, wait for file change and interval.
* This function exits if {@link InterruptedException} is occurred.
* @param baseDirectory
* @param interval
* @param handler
*/
public void watch(File baseDirectory, Duration interval, Runnable handler) {
while (true) {
try {
handler.run();
try (val watchService = FileSystems.getDefault().newWatchService()) {
register(watchService, baseDirectory);
log.info("Waiting for change of file or directory in {}", baseDirectory.getAbsolutePath());
waitForFileChange(watchService);
log.info("File or directory has been changed, waiting {} sec...", interval.getSeconds());
Thread.sleep(interval.toMillis());
} catch (InterruptedException e) {
log.info("Thread has been interrupted: {}", e.toString());
return;
}
} catch (Exception e1) {
log.warn("Error occurred while watching directory, retrying...", e1);
try {
Thread.sleep(interval.toMillis());
} catch (InterruptedException e2) {
log.info("Thread has been interrupted: {}", e2.toString());
return;
}
}
}
}