下面列出了怎么用java.nio.file.FileSystem的API类实例代码及写法,或者点击链接到github查看源代码。
public AthenzCredentialsMaintainer(URI ztsEndpoint,
Path trustStorePath,
ConfigServerInfo configServerInfo,
String certificateDnsSuffix,
ServiceIdentityProvider hostIdentityProvider,
boolean useInternalZts,
Clock clock,
FileSystem fileSystem) {
this.ztsEndpoint = ztsEndpoint;
this.trustStorePath = trustStorePath;
this.configserverIdentity = configServerInfo.getConfigServerIdentity();
this.csrGenerator = new CsrGenerator(certificateDnsSuffix, configserverIdentity.getFullName());
this.hostIdentityProvider = hostIdentityProvider;
this.fileSystem = fileSystem;
this.identityDocumentClient = new DefaultIdentityDocumentClient(
configServerInfo.getLoadBalancerEndpoint(),
hostIdentityProvider,
new AthenzIdentityVerifier(Set.of(configserverIdentity)));
this.clock = clock;
this.useInternalZts = useInternalZts;
}
private void initDataDirectory(final boolean isPivotBlockHeaderFileExist)
throws NoSuchFieldException {
final File pivotBlockHeaderFile = mock(File.class);
when(pivotBlockHeaderFile.isFile()).thenReturn(isPivotBlockHeaderFileExist);
when(pivotBlockHeaderFile.isDirectory()).thenReturn(true);
final File fastSyncDirFile = mock(File.class);
when(fastSyncDirFile.isDirectory()).thenReturn(true);
final Path storagePath = mock(Path.class);
final FileSystem fileSystem = mock(FileSystem.class);
when(storagePath.getFileSystem()).thenReturn(fileSystem);
when(fileSystem.provider()).thenReturn(mock(FileSystemProvider.class));
final Path pivotBlockHeaderPath = mock(Path.class);
when(pivotBlockHeaderPath.toFile()).thenReturn(pivotBlockHeaderFile);
when(pivotBlockHeaderPath.resolve(anyString())).thenReturn(storagePath);
final Path fastSyncDir = mock(Path.class);
when(fastSyncDir.resolve(any(String.class))).thenReturn(pivotBlockHeaderPath);
when(fastSyncDir.toFile()).thenReturn(fastSyncDirFile);
when(dataDirectory.resolve(anyString())).thenReturn(fastSyncDir);
}
private boolean isOSGiBundle(Path bundlePath, String bundleSymbolicName) throws IOException, CarbonToolException {
if (Files.exists(bundlePath)) {
boolean validSymbolicName, exportPackageAttributeCheck, importPackageAttributeCheck;
try (FileSystem zipFileSystem = BundleGeneratorUtils.createZipFileSystem(bundlePath, false)) {
Path manifestPath = zipFileSystem.getPath(Constants.JAR_MANIFEST_FOLDER, Constants.MANIFEST_FILE_NAME);
Manifest manifest = new Manifest(Files.newInputStream(manifestPath));
Attributes attributes = manifest.getMainAttributes();
String actualBundleSymbolicName = attributes.getValue(Constants.BUNDLE_SYMBOLIC_NAME);
validSymbolicName = ((actualBundleSymbolicName != null) && ((bundleSymbolicName != null)
&& bundleSymbolicName.equals(actualBundleSymbolicName)));
exportPackageAttributeCheck = attributes.getValue(Constants.EXPORT_PACKAGE) != null;
importPackageAttributeCheck = attributes.getValue(Constants.DYNAMIC_IMPORT_PACKAGE) != null;
}
return (validSymbolicName && exportPackageAttributeCheck && importPackageAttributeCheck);
} else {
return false;
}
}
/**
* 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 synchronized FileSystem open(URI uri) throws IOException {
FileSystem ret = null;
try {
ret = FileSystems.getFileSystem(uri);
} catch (FileSystemNotFoundException e) { }
boolean opened;
if (ret == null) {
ret = FileSystems.newFileSystem(uri, Collections.emptyMap());
opened = true;
} else {
opened = false;
}
RefData data = fsRefs.get(ret);
if (data == null) {
fsRefs.put(ret, new RefData(opened, 1));
} else {
data.refs++;
}
return ret;
}
@Override
public FileSystem newFileSystem(Path fakeRoot, Map<String,?> env)
throws IOException
{
if (env != null && env.keySet().contains("IOException")) {
triggerEx("IOException");
}
synchronized (FaultyFSProvider.class) {
if (delegate != null && delegate.isOpen())
throw new FileSystemAlreadyExistsException();
FaultyFileSystem result = new FaultyFileSystem(fakeRoot);
delegate = result;
return result;
}
}
public static LocalComputationConfig load(PlatformConfig platformConfig, FileSystem fileSystem) {
Objects.requireNonNull(platformConfig);
Path localDir = getDefaultLocalDir(fileSystem);
int availableCore = DEFAULT_AVAILABLE_CORE;
if (platformConfig.moduleExists(CONFIG_MODULE_NAME)) {
ModuleConfig config = platformConfig.getModuleConfig(CONFIG_MODULE_NAME);
localDir = getTmpDir(config, "tmp-dir")
.orElseGet(() -> getTmpDir(config, "tmpDir")
.orElseGet(() -> getDefaultLocalDir(fileSystem)));
availableCore = config.getOptionalIntProperty("available-core")
.orElseGet(() -> config.getOptionalIntProperty("availableCore")
.orElse(DEFAULT_AVAILABLE_CORE));
}
if (availableCore <= 0) {
availableCore = Runtime.getRuntime().availableProcessors();
}
return new LocalComputationConfig(localDir, availableCore);
}
private JavaFileObject getFileForInput(Location location, String relativePath)
throws IOException {
for (Path p: getLocation(location)) {
if (isDirectory(p)) {
Path f = resolve(p, relativePath);
if (Files.exists(f))
return PathFileObject.createDirectoryPathFileObject(this, f, p);
} else {
FileSystem fs = getFileSystem(p);
if (fs != null) {
Path file = getPath(fs, relativePath);
if (Files.exists(file))
return PathFileObject.createJarPathFileObject(this, file);
}
}
}
return null;
}
@Override
public FileSystem newFileSystem(Path fakeRoot, Map<String,?> env)
throws IOException
{
if (env != null && env.keySet().contains("IOException")) {
triggerEx("IOException");
}
synchronized (FaultyFSProvider.class) {
if (delegate != null && delegate.isOpen())
throw new FileSystemAlreadyExistsException();
FaultyFileSystem result = new FaultyFileSystem(fakeRoot);
delegate = result;
return result;
}
}
@Test
public void testToTask() throws Exception {
Network network = PhaseShifterTestCaseFactory.create();
PhaseTapChanger tapChanger = network.getTwoWindingsTransformer("PS1").getPhaseTapChanger();
assertEquals(1, tapChanger.getTapPosition());
TapChangeAction action = new TapChangeAction("PS1", 2);
ModificationTask task = action.toTask();
try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) {
Path localDir = fileSystem.getPath("/tmp");
ComputationManager computationManager = new LocalComputationManager(localDir);
task.modify(network, computationManager);
assertEquals(2, tapChanger.getTapPosition());
try {
action.toTask(null);
fail();
} catch (UnsupportedOperationException exc) {
}
}
}
static LuaFunction loadTextChunkFromFile(FileSystem fileSystem, ChunkLoader loader, String fileName, ByteString modeString, Object env)
throws LoaderException {
final LuaFunction fn;
try {
Path p = fileSystem.getPath(fileName);
if (!modeString.contains((byte) 't')) {
throw new LuaRuntimeException("attempt to load a text chunk (mode is '" + modeString + "')");
}
// FIXME: this is extremely wasteful!
byte[] bytes = Files.readAllBytes(p);
ByteString chunkText = ByteString.copyOf(bytes);
fn = loader.loadTextChunk(new Variable(env), fileName, chunkText.toString());
}
catch (InvalidPathException | IOException ex) {
throw new LoaderException(ex, fileName);
}
if (fn == null) {
throw new LuaRuntimeException("loader returned nil");
}
return fn;
}
public static Index indexTestClasses(Class<?> testClass) {
final Indexer indexer = new Indexer();
final Path testClassesLocation = getTestClassesLocation(testClass);
try {
if (Files.isDirectory(testClassesLocation)) {
indexTestClassesDir(indexer, testClassesLocation);
} else {
try (FileSystem jarFs = FileSystems.newFileSystem(testClassesLocation, null)) {
for (Path p : jarFs.getRootDirectories()) {
indexTestClassesDir(indexer, p);
}
}
}
} catch (IOException e) {
throw new UncheckedIOException("Unable to index the test-classes/ directory.", e);
}
return indexer.complete();
}
private static void z2zmove(FileSystem src, FileSystem dst, String path)
throws IOException
{
Path srcPath = src.getPath(path);
Path dstPath = dst.getPath(path);
if (Files.isDirectory(srcPath)) {
if (!Files.exists(dstPath))
mkdirs(dstPath);
try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {
for (Path child : ds) {
z2zmove(src, dst,
path + (path.endsWith("/")?"":"/") + child.getFileName());
}
}
} else {
//System.out.println("moving..." + path);
Path parent = dstPath.getParent();
if (parent != null && Files.notExists(parent))
mkdirs(parent);
Files.move(srcPath, dstPath);
}
}
@Override
public FileSystem newFileSystem(Path fakeRoot, Map<String,?> env)
throws IOException
{
if (env != null && env.keySet().contains("IOException")) {
triggerEx("IOException");
}
synchronized (FaultyFSProvider.class) {
if (delegate != null && delegate.isOpen())
throw new FileSystemAlreadyExistsException();
FaultyFileSystem result = new FaultyFileSystem(fakeRoot);
delegate = result;
return result;
}
}
public void testRotatingPlatters() throws Exception {
assumeFalse("windows is not supported", Constants.WINDOWS);
Path dir = createTempDir();
dir = FilterPath.unwrap(dir).toRealPath();
// fake ssd
FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz1)", "reiser4", "/dev/zzz1");
// make a fake /dev/zzz1 for it
Path devdir = dir.resolve("dev");
Files.createDirectories(devdir);
Files.createFile(devdir.resolve("zzz1"));
// make a fake /sys/block/zzz/queue/rotational file for it
Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
Files.createDirectories(sysdir);
try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
o.write("1\n".getBytes(StandardCharsets.US_ASCII));
}
Map<String,FileStore> mappings = Collections.singletonMap(dir.toString(), root);
FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
Path mockPath = mockLinux.getPath(dir.toString());
assertTrue(IOUtils.spinsLinux(mockPath));
}
@SuppressWarnings("unchecked")
private static ImmutableList<BuildFileParseExceptionStackTraceEntry> parseStackTrace(
Map<String, Object> exceptionMap, FileSystem fileSystem) {
List<Map<String, Object>> traceback =
(List<Map<String, Object>>) Objects.requireNonNull(exceptionMap.get("traceback"));
ImmutableList.Builder<BuildFileParseExceptionStackTraceEntry> stackTraceBuilder =
ImmutableList.builder();
for (Map<String, Object> tracebackItem : traceback) {
stackTraceBuilder.add(
BuildFileParseExceptionStackTraceEntry.of(
fileSystem.getPath((String) Objects.requireNonNull(tracebackItem.get("filename"))),
(Number) Objects.requireNonNull(tracebackItem.get("line_number")),
(String) Objects.requireNonNull(tracebackItem.get("function_name")),
(String) Objects.requireNonNull(tracebackItem.get("text"))));
}
return stackTraceBuilder.build();
}
/**
* Finds all files in an apk that match a given regular expression.
*
* @param apkFile The {@link FileSystem} representation of the apk zip archive.
* @param matcher A {@link PathMatcher} to match the requested filenames.
* @return A list of paths matching the provided matcher.
* @throws IOException Thrown if a matching file cannot be read from the apk.
*/
public static ImmutableList<Path> findFiles(FileSystem apkFile, PathMatcher matcher)
throws IOException {
ImmutableList.Builder<Path> result = ImmutableList.builder();
Path root = apkFile.getPath("/");
Files.walkFileTree(
root,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path p, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(p) || matcher.matches(p.normalize())) {
result.add(
// fancy way of eliding leading slash
root.relativize(p));
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
return FileVisitResult.SKIP_SUBTREE;
}
});
return result.build();
}
public FileSystem openConnection() throws IOException {
if (Files.notExists(getLocation())) {
// I can't use Map.of("create", "true") since the overload taking a path was only added in JDK 13
// and using URI overload doesn't support nested zip files
try (OutputStream out = Files.newOutputStream(getLocation(), StandardOpenOption.CREATE_NEW)) {
// End of Central Directory Record (EOCD)
out.write(new byte[] { 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
}
}
try {
return FileSystems.newFileSystem(getLocation(), (ClassLoader) null);
} catch (ProviderNotFoundException e) {
ModuleFinder.ofSystem()
.find("jdk.zipfs")
.orElseThrow(() -> new ProviderNotFoundException(
"Accessing the archive depends on the jdk.zipfs module which is missing from the JRE image"));
throw e;
}
}
/**
* Thread-safe ClosedFileSystemException test
*
* @return
*/
protected FileSystem getOrigFS() {
FileSystem orig = origFS;
if (orig == null || !orig.isOpen()) {
throw new ClosedFileSystemException();
}
return orig;
}
FolderOrigin(FileSystem fs, Author author, String message, Path cwd,
boolean materializeOutsideSymlinks, boolean ignoreInvalidSymlinks) {
this.fs = Preconditions.checkNotNull(fs);
this.author = author;
this.message = message;
this.cwd = Preconditions.checkNotNull(cwd);
this.copySymlinkStrategy = ignoreInvalidSymlinks
? CopySymlinkStrategy.IGNORE_INVALID_SYMLINKS
: materializeOutsideSymlinks
? CopySymlinkStrategy.MATERIALIZE_OUTSIDE_SYMLINKS
: CopySymlinkStrategy.FAIL_OUTSIDE_SYMLINKS;
}
private FileSystem getFileSystem(Path p) throws IOException {
FileSystem fs = fileSystems.get(p);
if (fs == null) {
fs = FileSystems.newFileSystem(p, null);
fileSystems.put(p, fs);
}
return fs;
}
public static void main(String[] args) throws IOException {
FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
fs.getFileStores();
Files.walkFileTree(fs.getPath("/modules/java.desktop"), new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
file = file.subpath(2, file.getNameCount());
String name = file.toString();
if (name.endsWith(".class")) {
name = name.substring(0, name.indexOf(".")).replace('/', '.');
final Class<?> type;
try {
type = Class.forName(name, false, null);
} catch (Throwable e) {
return FileVisitResult.CONTINUE;
}
if (type.isAnnotationPresent(SwingContainer.class)) {
if (!Container.class.isAssignableFrom(type)) {
System.err.println("Wrong annotation for: " + type);
throw new RuntimeException();
}
}
}
return FileVisitResult.CONTINUE;
};
});
}
public void walkResources(FileVisitor<? super Path> visitor) throws URISyntaxException, IOException {
try (FileSystem zipFs =
FileSystems.newFileSystem(artifactURL.toURI(), new HashMap<>())) {
Path resourcesPath = zipFs.getPath("/resources");
if(Files.isDirectory(resourcesPath)) {
Files.walkFileTree(resourcesPath, visitor);
}
}
}
public TestAndroidNdkResolver(
FileSystem fileSystem,
ImmutableMap<String, String> environment,
AndroidBuckConfig config,
Optional<Path> ndkRoot,
Optional<String> ndkVersion) {
super(fileSystem, environment, config);
this.ndkRoot = ndkRoot;
this.ndkVersion = ndkVersion;
}
@Test
public void sendZipFileCompressionSize_2() throws IOException {
Path path = Files.createTempFile(null, ".zip");
Files.copy(this.getClass().getResourceAsStream("/zipFile.zip"), path, StandardCopyOption.REPLACE_EXISTING);
path.toFile().deleteOnExit();
try (FileSystem zipFs = FileSystems.newFileSystem(path, (ClassLoader) null)) {
Path fromZipFile = zipFs.getPath("/largeFile.txt");
long fileSize = Files.size(fromZipFile);
assertSendFile(out -> out.addHeader(HttpHeaderNames.CONTENT_LENGTH, "1245")
.sendFile(fromZipFile, 0, fileSize), true, 2048, (req, res) -> true);
}
}
private void prepareOriginExcludes(String content) throws IOException {
FileSystem fileSystem = Jimfs.newFileSystem();
Path base = fileSystem.getPath("excludesTest");
Path folder = workdir.resolve("folder");
Files.createDirectories(folder);
touchFile(base, "folder/file.txt", content);
touchFile(base, "folder/subfolder/file.txt", content);
touchFile(base, "folder/subfolder/file.java", content);
touchFile(base, "folder2/file.txt", content);
touchFile(base, "folder2/subfolder/file.txt", content);
touchFile(base, "folder2/subfolder/file.java", content);
origin.addChange(1, base, "excludes", /*matchesGlob=*/true);
}
private void importExport(String ts, ReadOnlyDataSource ds, FileSystem fs) throws IOException {
CgmesImport i = new CgmesImport();
Properties importParameters = new Properties();
importParameters.put("powsyblTripleStore", ts);
importParameters.put("storeCgmesModelAsNetworkExtension", "true");
Network n = i.importData(ds, importParameters);
CgmesModel cgmes = n.getExtension(CgmesModelExtension.class).getCgmesModel();
cgmes.print(LOG::info);
CgmesExport e = new CgmesExport();
Path exportFolder = fs.getPath("impl-" + ts);
Files.createDirectories(exportFolder);
DataSource exportDataSource = new FileDataSource(exportFolder, "");
e.export(n, new Properties(), exportDataSource);
}
@Test
public void pathSpecResolvesToExpectedSetOfFiles() throws IOException {
FileSystem fs = Jimfs.newFileSystem();
Path baseDir = fs.getPath("/root");
Path foo = baseDir.resolve("foo.js");
Path bar = baseDir.resolve("a/bar.js");
Path baz = baseDir.resolve("a/b/baz.js");
Path quux = baseDir.resolve("a/b/c/quux.js");
Path quot = baseDir.resolve("a/b/c/quot.js");
Path otherDir = fs.getPath("/other");
Path otherFooTest = otherDir.resolve("a/b/foo_test.js");
Path otherBarTest = otherDir.resolve("a/bar_test.js");
Files.createDirectories(quux.getParent());
Files.createDirectories(otherFooTest.getParent());
Files.createFile(foo);
Files.createFile(bar);
Files.createFile(baz);
Files.createFile(quux);
Files.createFile(quot);
Files.createFile(otherFooTest);
Files.createFile(otherBarTest);
assertContentsAnyOrder(getPaths(baseDir, ""), foo, bar, baz, quux, quot);
assertContentsAnyOrder(getPaths(baseDir, "foo.js"), foo);
assertContentsAnyOrder(getPaths(baseDir, "a"), bar, baz, quux, quot);
assertContentsAnyOrder(getPaths(baseDir, "a/b"), baz, quux, quot);
assertContentsAnyOrder(getPaths(baseDir, "a/b/c"), quux, quot);
assertContentsAnyOrder(getPaths(baseDir, "*.js"), foo);
assertContentsAnyOrder(getPaths(baseDir, "a/b/*.js"), baz);
assertContentsAnyOrder(getPaths(baseDir, "a/b/c/*.js"), quux, quot);
assertContentsAnyOrder(getPaths(baseDir, "**.js"), foo, bar, baz, quux, quot);
assertContentsAnyOrder(getPaths(baseDir, "a/**.js"), bar, baz, quux, quot);
assertContentsAnyOrder(getPaths(baseDir, otherDir + "/a/*.js"), otherBarTest);
assertContentsAnyOrder(
getPaths(baseDir, otherDir + "/a/**_test.js"), otherBarTest, otherFooTest);
}
@Test
public void deleteRecursivelyIfExistsDoesNotFollowSymlinks() throws IOException {
FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
Path linkTarget = vfs.getPath("/link-target");
Path linkSource = vfs.getPath("/link-source");
Files.createDirectory(linkTarget);
Files.createSymbolicLink(linkSource, linkTarget);
MostFiles.deleteRecursivelyIfExists(linkSource);
// link is deleted, but target should still exist
assertTrue(Files.exists(linkTarget));
assertFalse(Files.exists(linkSource));
}
@Test
public void objectClassSizeTest() throws Exception {
String path = "/modules/java.base/java/lang/Object.class";
FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
Path classFile = fs.getPath(path);
assertTrue(Files.size(classFile) > 0L);
}