下面列出了怎么用java.nio.file.FileSystems的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public String call() throws Exception {
ModuleLayer parentLayer = ModuleLayer.boot();
// Obtain the parent Configuration
Path modulePath = FileSystems.getDefault().getPath(System.getProperty("module.path"));
ModuleFinder moduleFinder = ModuleFinder.of(modulePath);
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
Configuration cf1 = parentLayer.configuration()
.resolve(moduleFinder, ModuleFinder.of(), Set.of("java.logging"));
ModuleLayer layer1 = parentLayer.defineModulesWithManyLoaders(cf1, systemClassLoader);
ClassLoader cl = layer1.findLoader("java.logging");
assertNull("ClassLoader returned not-null for a bootstrap "
+ "class being loaded in a non-boot layer", cl);
System.out.println("Thread : " + Thread.currentThread().getName() + " done!");
return null;
}
@Before
public void setUp() throws Exception {
File logsBase = new File(System.getProperty("tomcat.test.temp", "output/tmp"));
if (!logsBase.mkdirs() && !logsBase.isDirectory()) {
Assert.fail("Unable to create logs directory.");
}
Path logsBasePath = FileSystems.getDefault().getPath(logsBase.getAbsolutePath());
logsDir = Files.createTempDirectory(logsBasePath, "test").toFile();
generateLogFiles(logsDir, PREFIX_1, SUFIX_2, 3);
generateLogFiles(logsDir, PREFIX_2, SUFIX_1, 3);
generateLogFiles(logsDir, PREFIX_3, SUFIX_1, 3);
generateLogFiles(logsDir, PREFIX_4, SUFIX_1, 3);
Calendar date = Calendar.getInstance();
date.add(Calendar.DAY_OF_MONTH, -3);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss.SSS");
File file = new File(logsDir, PREFIX_1 + formatter.format(date.getTime()) + SUFIX_1);
file.createNewFile();
}
@Test
public void includeResourcesInBundle() throws Exception {
Path bundle = FileSystems.getDefault().getPath("target/classes/META-INF/syndesis/schemas/dstu3/bundle.json");
String inspection;
try (InputStream fileIn = Files.newInputStream(bundle)) {
inspection = IOUtils.toString(fileIn, StandardCharsets.UTF_8);
}
String inspectionWithResources = FhirMetadataRetrieval.includeResources(inspection, "patient", "account");
ObjectMapper mapper = io.atlasmap.v2.Json.mapper();
XmlDocument xmlDocument = mapper.readValue(inspectionWithResources, XmlDocument.class);
XmlComplexType resource = (XmlComplexType) xmlDocument.getFields().getField().get(0);
Assertions.assertThat(resource.getName()).isEqualTo("tns:Bundle");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Patient");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Patient", "tns:contained", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Patient");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Patient", "tns:contained", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:resource", "tns:Account", "tns:contained", "tns:Patient");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Account");
assertCorrectPath(resource, "tns:Bundle", "tns:entry", "tns:response", "tns:outcome", "tns:Account", "tns:contained", "tns:Patient");
}
@Override
public void uploadMissingConfigFiles(SolrZkClient zkClient, ZkConfigManager zkConfigManager, String configName) throws IOException {
logger.info("Check any of the configs files are missing for config ({})", configName);
for (String configFile : configFiles) {
if ("enumsConfig.xml".equals(configFile) && !hasEnumConfig) {
logger.info("Config file ({}) is not needed for {}", configFile, configName);
continue;
}
String zkPath = String.format("%s/%s", configName, configFile);
if (zkConfigManager.configExists(zkPath)) {
logger.info("Config file ({}) has already uploaded properly.", configFile);
} else {
logger.info("Config file ({}) is missing. Reupload...", configFile);
FileSystems.getDefault().getSeparator();
uploadFileToZk(zkClient,
String.format("%s%s%s", getConfigSetFolder(), FileSystems.getDefault().getSeparator(), configFile),
String.format("%s%s", "/configs/", zkPath));
}
}
}
@Override
public void init() {
if (!enabled) {
LOG.info("File watcher loaded but not enabled: {}", this.toString());
return;
}
Path configFilePath = this.fileConfiguration.getPath();
LOG.info("Adding watch on '{}'.", configFilePath);
try {
this.watchService = FileSystems.getDefault().newWatchService();
Path parent = configFilePath.getParent();
if (parent == null) {
throw new ConfigurationError("Can not get parent directory of config file");
}
parent.register(this.watchService, StandardWatchEventKinds.ENTRY_MODIFY);
} catch (IOException e) {
throw new ConfigurationError("Error creating and registering watch service", e);
}
executor.submit(new Watcher(this.watchService, this.settingsService, this.fileConfiguration));
}
private void startEmulator() throws IOException, InterruptedException {
boolean configPresent = Files.exists(EMULATOR_CONFIG_PATH);
WatchService watchService = null;
if (configPresent) {
watchService = FileSystems.getDefault().newWatchService();
EMULATOR_CONFIG_DIR.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
}
try {
this.emulatorProcess = new ProcessBuilder("gcloud", "beta", "emulators", "pubsub", "start")
.start();
}
catch (IOException ex) {
fail("Gcloud not found; leaving host/port uninitialized.");
}
if (configPresent) {
updateConfig(watchService);
watchService.close();
}
else {
createConfig();
}
}
/**
* The main method for the ZipCat program. Run the program with an empty
* argument list to see possible arguments.
*
* @param args the argument list for ZipCat
*/
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: ZipCat zipfile fileToPrint");
}
/*
* Creates AutoCloseable FileSystem and BufferedReader.
* They will be closed automatically after the try block.
* If reader initialization fails, then zipFileSystem will be closed
* automatically.
*/
try (FileSystem zipFileSystem
= FileSystems.newFileSystem(Paths.get(args[0]),null);
InputStream input
= Files.newInputStream(zipFileSystem.getPath(args[1]))) {
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) != -1) {
System.out.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) throws Exception {
// create a bunch of directories. Create two tasks for each directory,
// one to bash on cancel, the other to poll the events
ExecutorService pool = Executors.newCachedThreadPool();
try {
Path top = Files.createTempDirectory("work");
top.toFile().deleteOnExit();
for (int i=1; i<=16; i++) {
Path dir = Files.createDirectory(top.resolve("dir-" + i));
WatchService watcher = FileSystems.getDefault().newWatchService();
pool.submit(() -> handle(dir, watcher));
pool.submit(() -> poll(watcher));
}
} finally {
pool.shutdown();
}
// give thread pool lots of time to terminate
if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
throw new RuntimeException("Thread pool did not terminate");
if (failed)
throw new RuntimeException("Test failed, see log for details");
}
public static void main(String[] args) {
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
try {
Path tmpFile = Files.createTempFile(customBaseDir, customFilePrefix, customFileSuffix);
System.out.println("Created as: " + tmpFile);
System.out.println("Sleep for 10 seconds until deletion ...");
File asFile = tmpFile.toFile();
asFile.deleteOnExit();
// simulate some operations with temp file until delete it
Thread.sleep(10000);
} catch (IOException | InterruptedException e) {
// handle exception, don't print it as below
System.err.println(e);
}
System.out.println("Delete file completed ...");
}
/**
* Make sure the {@literal actionchains} subdir exists.
* @return the {@link Path} of the {@literal} actionchains directory
*/
private Path createActionChainsDir() {
Path targetDir = getTargetDir();
if (!Files.exists(targetDir)) {
try {
Files.createDirectories(targetDir);
if (!skipSetOwner) {
FileSystem fileSystem = FileSystems.getDefault();
UserPrincipalLookupService service = fileSystem.getUserPrincipalLookupService();
UserPrincipal tomcatUser = service.lookupPrincipalByName("tomcat");
Files.setOwner(targetDir, tomcatUser);
}
}
catch (IOException e) {
LOG.error("Could not create action chain directory " + targetDir, e);
throw new RuntimeException(e);
}
}
return targetDir;
}
/**
* Test the URI of every file in the jrt file system
*/
@Test
public void testToAndFromUri() throws Exception {
FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
Path top = fs.getPath("/");
try (Stream<Path> stream = Files.walk(top)) {
stream.forEach(path -> {
URI u = path.toUri();
assertTrue(u.getScheme().equalsIgnoreCase("jrt"));
assertFalse(u.isOpaque());
assertTrue(u.getAuthority() == null);
assertEquals(u.getPath(), path.toAbsolutePath().toString());
Path p = Paths.get(u);
assertEquals(p, path);
});
}
}
private Map<Integer, FileSystem> createZips() throws IOException {
var loader = getClass().getClassLoader();
var map = new HashMap<Integer, FileSystem>();
for (int year = 2018; year < 2030; year++) {
var zipfile = cache.resolve(bucketName + "-" + year + ".zip");
if (Files.notExists(zipfile)) {
continue;
}
LOG.log(INFO, "Creating cache file system from {0}...", zipfile);
var zipFileSystem = FileSystems.newFileSystem(zipfile, loader);
if (LOG.isLoggable(INFO)) {
var count = Files.list(zipFileSystem.getPath("/")).count();
LOG.log(INFO, "{0} entries in {1}", count, zipFileSystem);
}
map.put(year, zipFileSystem);
}
return map;
}
/**
* This method initializes private data members of this class and also creates the Control File.
*
* @param directory The root directory of Storage where the transaction data is stored.
* @param segmentSizeThreshold The maximum size of each Segment.
* @param numPartitions The total number of partitions in the cluster.
* @param key The cluster key.
* @throws StorageException
* @throws IOException
*/
public StorageManager(String directory, long segmentSizeThreshold, int numPartitions, UUID key, int segmentCacheCapacity) throws IOException, StorageException {
logger.debug("StorageManager constructor is called");
this.directory = FileSystems.getDefault().getPath(directory);
this.partitions = new HashMap<>();
this.segmentSizeThreshold = segmentSizeThreshold;
this.segmentCacheCapacity = segmentCacheCapacity;
this.controlFile = new ControlFile(key, this.directory.resolve(ControlFile.FILE_NAME), numPartitions, true);
logger.debug("storage opened: directory={}", directory);
for (int id : controlFile.getPartitionIds()) {
if (controlFile.getPartitionInfo(id).getSnapshot().isAssigned) {
createPartition(id);
}
}
}
@Test
public void testRemovePartitionWithoutFilePreserve() throws ConcurrentUpdateException, IOException, StorageException {
int partitionId = new Random().nextInt(NUM_PARTITION);
String fileNameFormat = "%019d.%s";
File dir = Files.createTempDirectory("StorageManagerTest-").toFile();
Path partitionDir = FileSystems.getDefault().getPath(dir.getPath()).resolve(Integer.toString(partitionId));
Path segPath = partitionDir.resolve(String.format(fileNameFormat, 0L, "seg"));
Path idxPath = partitionDir.resolve(String.format(fileNameFormat, 0L, "idx"));
StorageManager manager = new StorageManager(dir.getPath(), WaltzStorageConfig.DEFAULT_SEGMENT_SIZE_THRESHOLD, NUM_PARTITION, clusterKey, WaltzStorageConfig.DEFAULT_STORAGE_SEGMENT_CACHE_CAPACITY);
try {
manager.open(clusterKey, NUM_PARTITION);
manager.setPartitionAssignment(partitionId, true, false);
manager.setPartitionAssignment(partitionId, false, true);
assertFalse(segPath.toFile().exists());
assertFalse(idxPath.toFile().exists());
} finally {
manager.close();
}
}
private static FileSystem getFileSystem(URI jarUri) {
FileSystem fs = fileSystems.get(jarUri);
if (fs == null) {
synchronized (fileSystems) {
fs = fileSystems.get(jarUri);
if (fs == null) {
try {
fs = FileSystems.getFileSystem(jarUri);
} catch (FileSystemNotFoundException e1) {
try {
fs = FileSystems.newFileSystem(jarUri, Collections.emptyMap());
} catch (IOException e2) {
throw new IllegalStateException("Could not create FileSystem for " + jarUri, e2);
}
}
fileSystems.put(jarUri, fs);
}
}
}
return fs;
}
/**
* This call is not thread safe, a single of FileSystem can be created for the
* profided uri until it is closed.
*
* @param uri The uri to the zip file.
* @param env Env map.
* @return A new FileSystem.
* @throws IOException in case of a failure
*/
public static FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
// If Multi threading required, logic should be added to wrap this fs
// onto a fs that handles a reference counter and close the fs only when all thread are done
// with it.
try {
return FileSystems.newFileSystem(uri, env);
} catch (IOException | ZipError ioe) {
// TODO: (at a later date) Get rid of the ZipError catching (and instead only catch IOException)
// since it's a JDK bug which threw the undeclared ZipError instead of an IOException.
// Java 9 fixes it https://bugs.openjdk.java.net/browse/JDK-8062754
// include the URI for which the filesystem creation failed
throw new IOException("Failed to create a new filesystem for " + uri, ioe);
}
}
public static void generateDummyPlatform(Path destination, String version) throws IOException, URISyntaxException {
Path targetZip = destination.resolve(String.format("hybris-commerce-suite-%s.zip", version));
Map<String, String> env = new HashMap<>();
env.put("create", "true");
try (FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + targetZip.toUri().toString()), env, null)) {
Path sourceDir = Paths.get(TestUtils.class.getResource("/dummy-platform").toURI());
Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relative = sourceDir.relativize(file);
if (relative.getParent() != null) {
Path path = zipfs.getPath(relative.getParent().toString());
Files.createDirectories(path);
}
Path target = zipfs.getPath(relative.toString());
Files.copy(file, target);
return super.visitFile(file, attrs);
}
});
String build = String.format("version=%s\n", version);
Path buildNumber = zipfs.getPath("hybris", "bin", "platform", "build.number");
Files.write(buildNumber, build.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
}
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");
}
}
static Stream<Path> jrtPaths() {
FileSystem jrt = FileSystems.getFileSystem(URI.create("jrt:/"));
Path root = jrt.getPath("/");
try {
return Files.walk(root)
.filter(p -> p.getNameCount() > 1)
.filter(p -> p.toString().endsWith(".class"));
} catch (IOException x) {
throw new UncheckedIOException(x);
}
}
/**
* Appends a new file with name {@code filename} and contents
* {@code fileContents} into existing jar file with name {@code jarFile}.
*
* @param jarFile name of jar file to append
* @param filename name of new file to append in jar
* @param fileContents contents of new file to append in jar
* @throws IOException
*/
private static void appendJar(String jarFile, String filename, String fileContents) throws IOException {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jar:" + Paths.get(jarFile).toUri()), env)) {
try (Writer writer = Files.newBufferedWriter(fileSystem.getPath(filename), StandardCharsets.UTF_8,
StandardOpenOption.CREATE)) {
writer.write(fileContents);
}
}
}
private static void openAndCloseWatcher(Path dir) {
FileSystem fs = FileSystems.getDefault();
for (int i = 0; i < ITERATIONS_COUNT; i++) {
try (WatchService watcher = fs.newWatchService()) {
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException ioe) {
// ignore
}
}
}
private static String[] getLauncher() throws IOException {
String platform = getPlatform();
if (platform == null) {
return null;
}
String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
File.separator + "launcher";
final FileSystem FS = FileSystems.getDefault();
Path launcherPath = FS.getPath(launcher);
final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
Files.isReadable(launcherPath);
if (!hasLauncher) {
System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
return null;
}
// It is impossible to store an executable file in the source control
// We need to copy the launcher to the working directory
// and set the executable flag
Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
Files.copy(launcherPath, localLauncherPath,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
if (!Files.isExecutable(localLauncherPath)) {
Set<PosixFilePermission> perms = new HashSet<>(
Files.getPosixFilePermissions(
localLauncherPath,
LinkOption.NOFOLLOW_LINKS
)
);
perms.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(localLauncherPath, perms);
}
return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
private void handleIncludes(Vector<String> includes, Vector<BuildConfig> allConfigs) {
for (String path : includes) {
FileTreeCreatorVC7 ftc = new FileTreeCreatorVC7(FileSystems.getDefault().getPath(path) , allConfigs, this);
try {
ftc.writeFileTree();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test(expected = CommandLine.ExecutionException.class)
public void shouldFailIfOutputDirectoryNonEmpty() throws IOException {
runCmdAndCheckOutput(
cmd(),
"/operator/config_generate_keys.json",
FileSystems.getDefault().getPath("."),
"genesis.json",
true,
asList("key.pub", "key.priv"));
}
@Override
public String toString(final Object obj) {
final Path path = (Path)obj;
if (path.getFileSystem() == FileSystems.getDefault()) {
final String localPath = path.toString();
if (File.separatorChar != '/') {
return localPath.replace(File.separatorChar, '/');
} else {
return localPath;
}
} else {
return path.toUri().toString();
}
}
public void augmentclassPath(HashMap<String, ClassProvider> clsToClasspath){
synchronized(strToURI.computeIfAbsent(jarUri, (URI a) -> a)) {
try (FileSystem zipfs = FileSystems.newFileSystem(jarUri, env)) {
Path root = zipfs.getPath("/");
Files.walk(root).filter(a -> !Files.isDirectory(a) && a.toString().endsWith(".class")).forEach( a -> addToClsP(a.toString(), clsToClasspath) );
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void startWatchThread() throws IOException
{
if ( watchThread==null ) {
watchService = FileSystems.getDefault().newWatchService();
watchThread = new Thread(()->{
watchThreadFunc();
}, "File watch thread");
watchThread.setDaemon(true);
watchThread.start();
}
}
@Test
public void testSnapshot() throws Exception {
Path tempDir = Files.createTempDirectory(FileSystems.getDefault().getPath("./target"), null);
File file = null;
try {
KieServices ks = KieServices.Factory.get();
ReleaseId releaseId = ks.newReleaseId( "org.kie", "scanner-test", "1.0-SNAPSHOT" );
createKieJar( ks, releaseId, "R1" );
KieContainer kieContainer = ks.newKieContainer( releaseId );
KieSession ksession = kieContainer.newKieSession();
checkKSession( ksession, "R1" );
KieScanner scanner = ks.newKieScanner( kieContainer, tempDir.toString() );
scanner.scanNow();
ksession = kieContainer.newKieSession();
checkKSession( ksession, "R1" );
file = write( createKieJar( ks, releaseId, "R2" ), tempDir, releaseId );
ksession = kieContainer.newKieSession();
checkKSession( ksession, "R1" );
scanner.scanNow();
ksession = kieContainer.newKieSession();
checkKSession( ksession, "R2" );
} finally {
if (file != null) {
file.delete();
}
Files.delete(tempDir);
}
}
public static String[] getSupportedLanguages() {
ArrayList<Path> filesList = new ArrayList<>();
try {
URI uri = Utils.class.getResource("/rip.properties").toURI();
Path myPath;
if (uri.getScheme().equals("jar")) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
myPath = fileSystem.getPath("/");
} else {
myPath = Paths.get(uri).getParent();
}
Files.walk(myPath, 1).filter(p -> p.toString().contains("LabelsBundle_")).distinct()
.forEach(filesList::add);
String[] langs = new String[filesList.size()];
for (int i = 0; i < filesList.size(); i++) {
Matcher matcher = pattern.matcher(filesList.get(i).toString());
if (matcher.find())
langs[i] = matcher.group("lang");
}
return langs;
} catch (Exception e) {
e.printStackTrace();
// On error return default language
return new String[] { DEFAULT_LANG };
}
}
public synchronized static void init(String agentArguments, Instrumentation instrumentation, boolean premain) {
if (Boolean.getBoolean("ElasticApm.attached")) {
// agent is already attached; don't attach twice
// don't fail as this is a valid case
// for example, Spring Boot restarts the application in dev mode
return;
}
String javaVersion = System.getProperty("java.version");
String javaVmName = System.getProperty("java.vm.name");
if (!isJavaVersionSupported(javaVersion, javaVmName)) {
// Gracefully abort agent startup is better than unexpected failure down the road when we known a given JVM
// version is not supported. Agent might trigger known JVM bugs causing JVM crashes, notably on early Java 8
// versions (but fixed in later versions), given those versions are obsolete and agent can't have workarounds
// for JVM internals, there is no other option but to use an up-to-date JVM instead.
System.err.println(String.format("Failed to start agent - JVM version not supported: %s", javaVersion));
return;
}
try {
// workaround for classloader deadlock https://bugs.openjdk.java.net/browse/JDK-8194653
FileSystems.getDefault();
final File agentJarFile = getAgentJarFile();
try (JarFile jarFile = new JarFile(agentJarFile)) {
instrumentation.appendToBootstrapClassLoaderSearch(jarFile);
}
// invoking via reflection to make sure the class is not loaded by the system classloader,
// but only from the bootstrap classloader
Class.forName("co.elastic.apm.agent.bci.ElasticApmAgent", true, null)
.getMethod("initialize", String.class, Instrumentation.class, File.class, boolean.class)
.invoke(null, agentArguments, instrumentation, agentJarFile, premain);
System.setProperty("ElasticApm.attached", Boolean.TRUE.toString());
} catch (Exception e) {
System.err.println("Failed to start agent");
e.printStackTrace();
}
}