public static void main(String[] args) throws OptionsParsingException, IOException { FileSystem fileSystem = FileSystems.getDefault(); OptionsParser parser = OptionsParser.newOptionsParser(PlMergeOptions.class); parser.parse(args); PlMergeOptions options = parser.getOptions(PlMergeOptions.class); MergingArguments data = null; if (usingControlProtobuf(options)) { InputStream in = Files.newInputStream(fileSystem.getPath(options.controlPath)); Control control = Control.parseFrom(in); validateControl(control); data = new MergingArguments(control); } else if (usingCommandLineArgs(options)) { data = new MergingArguments(options); } else { missingArg("Either --control or --out_file and at least one --source_file"); } PlistMerging merging = PlistMerging.from( data, ImmutableMap.<String, NSObject>of(), new KeysToRemoveIfEmptyString("CFBundleIconFile", "NSPrincipalClass")); if (data.getPrimaryBundleId() != null || data.getFallbackBundleId() != null) { // Only set the bundle identifier if we were passed arguments to do so. // This prevents CFBundleIdentifiers being put into strings files. merging.setBundleIdentifier(data.getPrimaryBundleId(), data.getFallbackBundleId()); } merging.writePlist(fileSystem.getPath(data.getOutFile())); }
public static Path getPathInClasspath(URL resource) throws IOException, URISyntaxException { Objects.requireNonNull(resource, "Resource URL cannot be null"); URI uri = resource.toURI(); String scheme = uri.getScheme(); if (scheme.equals("file")) { return Paths.get(uri); } if (!scheme.equals("jar")) { throw new IllegalArgumentException("Cannot convert to Path: " + uri); } String s = uri.toString(); int separator = s.indexOf("!/"); String entryName = s.substring(separator + 2); URI fileURI = URI.create(s.substring(0, separator)); FileSystem fs = null; try { fs = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap()); } catch (FileSystemAlreadyExistsException e) { fs = FileSystems.getFileSystem(fileURI); } return fs.getPath(entryName); }
/** * Creates/opens a zip file at the specified location. Does <b>not</b> create parent folders. * * @param zipFile the path to the zip file * @param create true if the file should be created, if non-existent * @param rootFirst the root folder * @param rootMore the rest of the path * @throws IOException */ public ZipFileDataStore(Path zipFile, boolean create, String rootFirst, String... rootMore) throws IOException { URI zipUri = zipFile.toUri(); URI uri = URI.create("jar:file:" + zipUri.getPath()); FileSystem fileSys; try { fileSys = FileSystems.getFileSystem(uri); log.info("Opened existing file " + uri); } catch (FileSystemNotFoundException e) { // create must always be set: // if not a FileSystem without "create" could be created // and would be used ever after - there is no way a FileSystem could be removed Map<String, String> env = new HashMap<>(); env.put("create", "true"); fileSys = FileSystems.newFileSystem(uri, env); log.info("Created file " + uri); } this.zipFile = uri; this.fileSystem = fileSys; this.root = fileSys.getPath(rootFirst, rootMore).toAbsolutePath(); // checking if the root already exists is done in createDirs() if (create) { Files.createDirectories(root); } }
/** File store properties examined */ @Test public void testRetrieveFileStoreInforamtion() throws IOException { FileSystem fs = FileSystems.getDefault(); assertNotNull(fs); List<FileStore> stores = iterableToList(fs.getFileStores()); // file store is device such a drive, partition or volume // in my system I have 3 partitions assertEquals(3, stores.size()); // for storing triples of basic file store identification Set<String> storeNames = new HashSet<>(); for (FileStore store : stores) { storeNames.add(store.name() + ";" + store.type() + ";" + store.isReadOnly()); long total = store.getTotalSpace(); long unallocated = store.getUnallocatedSpace(); long usable = store.getUsableSpace(); assertTrue(total > 0); assertTrue(unallocated > 0 && total >= unallocated); assertTrue(usable > 0 && total >= usable); // Just for notice of NumberFormat class existence :) // System.out.println(NumberFormat.getInstance().format(total)); } // environment dependent assertEquals( cSET("Windows7_OS;NTFS;false", "Data;NTFS;false", "Documents;NTFS;false"), storeNames); // can be used for determine if file store supports such attribute view assertTrue(stores.get(0).supportsFileAttributeView(BasicFileAttributeView.class)); assertFalse(stores.get(0).supportsFileAttributeView(PosixFileAttributeView.class)); }
public static void saveData(String file, EnumMap<PlayerStats, Float> map, boolean overwrite) { FileSystem fileSystem = FileSystems.getDefault(); Path path = fileSystem.getPath(file); if (Files.isDirectory(path)) throw new IllegalArgumentException("This method is not supposed to read a directory"); if (Files.exists(path) && Files.isReadable(path)) { if (overwrite == false) return; } else try { Files.createFile(path); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(Files.newOutputStream(path))) { objectOutputStream.writeObject(map); } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
/** @throws IOException ShrinkWrap errors */ @Override protected void setupPathManager() throws IOException { final JavaArchive homeArchive = ShrinkWrap.create(JavaArchive.class); final FileSystem vfs = ShrinkWrapFileSystems.newFileSystem(homeArchive); PathManager.getInstance().useOverrideHomePath(vfs.getPath("")); PathManager.getInstance().setCurrentSaveTitle("world1"); }
public Path[] getJarPaths() { Path[] paths = new Path[this.jarFiles.length]; FileSystem fs = FileSystems.getDefault(); for (int index = 0; index < paths.length; index++) paths[index] = fs.getPath(this.jarFiles[index]); return paths; }
private Toolbox loadToolbox() throws IOException, URISyntaxException { Path foundPath = findToolsDir(); Toolbox box; if (Files.isDirectory(foundPath)) { box = new Toolbox(foundPath); Path tempDir = Files.createTempDirectory(TOOLS_DIR_NAME); Path tempZipFile = tempDir.resolve(TOOLS_ZIP_NAME); dirToZip(foundPath, tempZipFile); byte[] zipContents = Files.readAllBytes(tempZipFile); box.setZipContents(zipContents); Files.delete(tempZipFile); Files.delete(tempDir); } // found tools zip else { FileSystem fs = FileSystems.newFileSystem(foundPath, null); Path toolsPath = fs.getPath(TOOLS_DIR_NAME); box = new Toolbox(toolsPath); byte[] zipContents = Files.readAllBytes(foundPath); box.setZipContents(zipContents); } return box; }
public static void main(String[] args) { // String fileName = "READ"; String fileName = "test"; FileSystem fileSystem = FileSystems.getDefault(); Path root = fileSystem.getPath("./"); final Pattern pattern = Pattern.compile(fileName); FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { Matcher matcher = pattern.matcher(file.toString()); if (matcher.find()) { // マッチしたら、表示 System.out.println(file); } return FileVisitResult.CONTINUE; // return FileVisitResult.SKIP_SUBTREE; // http://docs.oracle.com/javase/jp/7/api/java/nio/file/FileVisitResult.html } }; try { Files.walkFileTree(root, visitor); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String[] args) throws OptionsParsingException, IOException { FileSystem fileSystem = FileSystems.getDefault(); OptionsParser parser = OptionsParser.newOptionsParser(PlMergeOptions.class); parser.parse(args); PlMergeOptions options = parser.getOptions(PlMergeOptions.class); if (options.controlPath == null) { missingArg("control"); } InputStream in = Files.newInputStream(fileSystem.getPath(options.controlPath)); Control control = Control.parseFrom(in); validateControl(control); PlistMerging merging = PlistMerging.from( control, new KeysToRemoveIfEmptyString("CFBundleIconFile", "NSPrincipalClass")); String primaryBundleId = Strings.emptyToNull(control.getPrimaryBundleId()); String fallbackBundleId = Strings.emptyToNull(control.getFallbackBundleId()); if (primaryBundleId != null || fallbackBundleId != null) { // Only set the bundle identifier if we were passed arguments to do so. // This prevents CFBundleIdentifiers being put into strings files. merging.setBundleIdentifier(primaryBundleId, fallbackBundleId); } merging.writePlist(fileSystem.getPath(control.getOutFile())); }
/** * 修改渠道号 * * <p>demo: <code>changeChannel("xxx../../my.apk", "hiapk");</code> * * @param zipFilename apk文件 * @param channel 新渠道号 * @return true or false */ public static boolean buildChannel(String zipFilename, String channelPrefix, String channel) { try (FileSystem zipfs = createZipFileSystem(zipFilename, false)) { String channelBegin = "/META-INF/" + channelPrefix; String channelFlagName = channelBegin + channel; final Path root = zipfs.getPath("/META-INF/"); ChannelFileVisitor visitor = new ChannelFileVisitor(channelBegin); Files.walkFileTree(root, visitor); Path existChannel = visitor.getChannelFile(); Path newChannel = zipfs.getPath(channelFlagName); if (existChannel != null) { Files.move(existChannel, newChannel, StandardCopyOption.ATOMIC_MOVE); } else { Files.createFile(newChannel); } return true; } catch (IOException e) { e.printStackTrace(); } return false; }
@Test public void test2() { FileSystem fs = FileSystems.getDefault(); Path child = fs.getPath("/tmp"); for (Path name : fs.getPath("/tmp").relativize(fs.getPath("/tmp/test/qwe"))) { child = child.resolve(name); } }
@Test public void test() throws Exception { FileSystem from = new DummyFileSystemProvider().getFileSystem(null); Path root = from.getRootDirectories().iterator().next(); for (Path p : from.provider().newDirectoryStream(root, null)) { System.out.println(p); } }
private static String read(String location, URI uri) throws Exception { try { FileSystem fileSystem = FileSystems.getFileSystem(uri); Path fsPath = fileSystem.getPath(location); return read(Files.newBufferedReader(fsPath, DEFAULT_CHARSET)); } catch (ProviderNotFoundException ex) { return read(uri.toURL().openStream()); } }
public static void main(String[] args) { Path path = Paths.get("/home/docs/users.txt"); FileSystem fileSystem = path.getFileSystem(); Set<String> supportedViews = fileSystem.supportedFileAttributeViews(); for (String view : supportedViews) { logger.debug(view); } }
public static void watchDirectoryPath(Path path) { // Sanity check - Check if path is a folder try { Boolean isFolder = (Boolean) Files.getAttribute(path, "basic:isDirectory", NOFOLLOW_LINKS); if (!isFolder) { throw new IllegalArgumentException("Path: " + path + " is not a folder"); } } catch (IOException ioe) { // Folder does not exists ioe.printStackTrace(); } // System.out.println("Watching path: " + path); // We obtain the file system of the Path FileSystem fs = path.getFileSystem(); // We create the new WatchService using the new try() block try (WatchService service = fs.newWatchService()) { // We register the path to the service // We watch for creation events path.register(service, ENTRY_CREATE); // Start the infinite polling loop WatchKey key = null; while (true) { key = service.take(); // Dequeueing events Kind<?> kind = null; for (WatchEvent<?> watchEvent : key.pollEvents()) { // Get the type of the event kind = watchEvent.kind(); if (OVERFLOW == kind) { continue; // loop } else if (ENTRY_CREATE == kind) { // A new Path was created // Path newPath = ((WatchEvent<Path>) // watchEvent).context(); // Output // System.out.println("New path created: " + newPath); } } if (!key.reset()) { break; // loop } } } catch (IOException ioe) { ioe.printStackTrace(); } catch (InterruptedException ie) { ie.printStackTrace(); } }
/** * Method to save the selected Experiment, in xml and xls (if possible), in a temporary folder. * The files will be contained inside a zip. * * @return String with the path of the zip file. * @throws IOException */ private String saveExpInTempFolder() throws IOException { String toRet = ""; // Create temporary File String filePath = Files.createTempDirectory("").toString() + "/"; filePath = filePath.replace("\\", "/"); // Get bioID String bioID = selExp.getBioID(); if (bioID.isEmpty()) { bioID = "bio_"; } DataToFile.saveXMLData(selExp, filePath + "xml"); // Only save in XLS if the Experiment is an IntraExperiment if (!isInter) { DataToFile.saveXLSData(selExp, filePath + "xls"); } // Generate ZIP file with Java 7 Map<String, String> zipProperties = new HashMap<>(); zipProperties.put("create", "true"); zipProperties.put("encoding", "UTF-8"); // Create zip file URI zipDisk; toRet = filePath + bioID + ".zip"; if (toRet.startsWith("/")) { zipDisk = URI.create("jar:file:" + toRet); } else { zipDisk = URI.create("jar:file:/" + toRet); } // Adding files to zip try (FileSystem zipfs = FileSystems.newFileSystem(zipDisk, zipProperties)) { // Create file inside zip Path zipFilePath = zipfs.getPath(bioID + ".xml"); // Path where the file to be added resides Path addNewFile = Paths.get(filePath + "xml.xml"); // Append file to ZIP File Files.copy(addNewFile, zipFilePath); if (!isInter) { // Now go for the xls file zipFilePath = zipfs.getPath(bioID + ".xls"); addNewFile = Paths.get(filePath + "xls.xls"); Files.copy(addNewFile, zipFilePath); } } // Delete temp files Files.deleteIfExists(Paths.get(filePath + "xml.xml")); Files.deleteIfExists(Paths.get(filePath + "xls.xls")); return toRet; }
public PathFilteringService(Path ignoreRulesFilePath) throws IOException { if (Files.exists(ignoreRulesFilePath)) { FileSystem fs = FileSystems.getDefault(); this.ignoreFilesRules = new ArrayList<PathMatcher>(); List<String> lines = Files.readAllLines(ignoreRulesFilePath, Charset.defaultCharset()); for (String line : lines) { this.ignoreFilesRules.add(fs.getPathMatcher("glob:" + line)); } } }
public static void main(String[] args) throws Exception { final FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/")); final Path root = fs.getPath("/modules"); final List<String> names = Files.walk(root) .filter(p -> p.getNameCount() > 2) .filter(p -> Layer.boot().findModule(p.getName(1).toString()).isPresent()) .map(p -> p.subpath(2, p.getNameCount())) .map(p -> p.toString()) .filter(s -> s.endsWith(".class") && !s.endsWith("module-info.class")) .collect(Collectors.toList()); Runnable r = new Runnable() { @Override public void run() { names.forEach( name -> { String cn = name.substring(0, name.length() - 6).replace('/', '.'); try { Class.forName(cn, false, ClassLoader.getSystemClassLoader()); } catch (Exception ex) { System.err.println(Thread.currentThread() + " " + ex.getClass()); } }); } }; Thread[] threads = new Thread[NTHREADS]; for (int i = 0; i < NTHREADS; i++) { Thread thread = new Thread(r); threads[i] = thread; thread.start(); } Thread.sleep(1); for (int i = 0; i < NTHREADS; i++) { Thread thread = threads[i]; if (thread.isAlive()) { thread.interrupt(); break; } } for (int i = 0; i < NTHREADS; i++) { Thread thread = threads[i]; thread.join(); } }
private static void eachLine(String location, URI uri, EachLine eachLine) throws Exception { try { FileSystem fileSystem = FileSystems.getFileSystem(uri); Path fsPath = fileSystem.getPath(location); BufferedReader buf = Files.newBufferedReader(fsPath, DEFAULT_CHARSET); eachLine(buf, eachLine); } catch (ProviderNotFoundException ex) { eachLine(uri.toURL().openStream(), eachLine); } }
public static void main(String[] args) throws IOException { Path jarfile = Paths.get("/home/punki/test.zip"); FileSystem fs = FileSystems.newFileSystem(jarfile, null); Path path = fs.getPath("tekst.txt"); System.out.println("path.toString() = " + path.toString()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Files.copy(path, outputStream); System.out.println("bytes = " + new String(outputStream.toByteArray())); List<String> lines = Files.readAllLines(path, Charset.defaultCharset()); for (String line : lines) { System.out.println("line = " + line); } }
public Schema load() throws IOException { ImmutableList<Path> directories = this.directories.build(); if (directories.isEmpty()) { throw new IllegalStateException("No directories added."); } Deque<Path> protos = new ArrayDeque<>(this.protos.build()); if (protos.isEmpty()) { // TODO traverse all files in every directory. } Map<Path, ProtoFile> loaded = new LinkedHashMap<>(); while (!protos.isEmpty()) { Path proto = protos.removeFirst(); if (loaded.containsKey(proto)) { continue; } ProtoFileElement element = null; for (Path directory : directories) { if (proto.isAbsolute() && !proto.startsWith(directory)) { continue; } Path resolvedPath = directory.resolve(proto); if (Files.exists(resolvedPath)) { Location location = Location.get(directory.toString(), proto.toString()); try (Source source = Okio.source(resolvedPath)) { String data = Okio.buffer(source).readUtf8(); element = ProtoParser.parse(location, data); } catch (IOException e) { throw new IOException("Failed to load " + proto, e); } break; } } if (element == null) { throw new FileNotFoundException("Failed to locate " + proto + " in " + directories); } ProtoFile protoFile = ProtoFile.get(element); loaded.put(proto, protoFile); // Queue dependencies to be loaded. FileSystem fs = proto.getFileSystem(); for (String importPath : element.imports()) { protos.addLast(fs.getPath(importPath)); } } return new Linker(loaded.values()).link(); }
private static List<String> readLines(String location, URI uri) throws Exception { try { String path = location; path = getWindowsPathIfNeeded(path); FileSystem fileSystem = FileSystems.getFileSystem(uri); Path fsPath = fileSystem.getPath(path); // Paths.get() return Files.readAllLines(fsPath, DEFAULT_CHARSET); } catch (ProviderNotFoundException ex) { return readLines(uri.toURL().openStream()); } }
public static void main(String[] args) throws IOException { System.out.format("%-20s %12s %12s %12s\n", "Filesystem", "kbytes", "used", "avail"); if (args.length == 0) { FileSystem fs = FileSystems.getDefault(); for (FileStore store : fs.getFileStores()) { printFileStore(store); } } else { for (String file : args) { FileStore store = Files.getFileStore(Paths.get(file)); printFileStore(store); } } }
public void dirToZip(final Path srcDir, Path destZip) throws IOException, URISyntaxException { logger.debug("packaging " + srcDir + " -> " + destZip); if (Files.exists(destZip)) { logger.info("deleting existing " + destZip); Files.delete(destZip); } // destZip.toUri() does not work URI zipLocation = new URI("jar:file:" + destZip); // create zip Map<String, String> env = new HashMap<String, String>(); env.put("create", "true"); final FileSystem zipFs = FileSystems.newFileSystem(zipLocation, env); // copy recursively Files.walkFileTree( srcDir, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { return copy(file); } public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return copy(dir); } private FileVisitResult copy(Path src) throws IOException { Path dest = src.subpath(srcDir.getNameCount() - 1, src.getNameCount()); Path destInZip = zipFs.getPath(dest.toString()); // permissions are not necessarily correct though, so they are also reset in comp Files.copy( src, destInZip, new CopyOption[] { StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING }); return FileVisitResult.CONTINUE; } }); zipFs.close(); }
@Override public void validate(Path zipFile, ApplicationData validationData) throws ApplicationUploadException { try { FileSystem fs = FileSystems.newFileSystem(zipFile, null); ValidationContext validationContext = new ValidationContext(); Files.walkFileTree(fs.getPath("/"), new ApplicationFileVisitor(validationContext)); for (ValidationRule rule : getValidationRules()) { rule.validate(validationContext, validationData); } } catch (IOException e) { throw new ApplicationUploadException(e); } }
@Before public void before() throws Exception { fileSystem = MemoryFileSystemBuilder.newEmpty().build("test"); defaultFile = TestUtil.storeFile( fileSystem.getPath("cpuinfo"), this.getClass().getResourceAsStream("cpuinfo.txt")); }
public PluginContext( PluginManager pluginManager, ClassLoader classLoader, PluginSourceType pluginType, URI location, Plugin plugin, PluginImplementation pluginImplementation, String classLocation) throws IOException { this.pluginManager = pluginManager; this.classLoader = classLoader; this.pluginType = pluginType; this.location = location; this.plugin = plugin; this.pluginImplementation = pluginImplementation; this.classLocation = classLocation; switch (pluginType) { case ECLIPSE_PROJECT: fileSystem = FileSystems.getDefault(); rootPath = Paths.get(location); break; case INTERNAL: break; case JAR_FILE: fileSystem = pluginManager.getOrCreateFileSystem(location); rootPath = fileSystem.getPath("/"); break; default: break; } }
public static void main(String[] args) { Stopwatch timer = Stopwatch.createStarted(); OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class); optionsParser.parseAndExitUponError(args); Options options = optionsParser.getOptions(Options.class); checkFlags(options); FileSystem fileSystem = FileSystems.getDefault(); Path working = fileSystem.getPath("").toAbsolutePath(); AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(new StdLogger(com.android.utils.StdLogger.Level.VERBOSE)); try { Path resourcesOut = Files.createTempDirectory("tmp-resources"); resourcesOut.toFile().deleteOnExit(); Path assetsOut = Files.createTempDirectory("tmp-assets"); assetsOut.toFile().deleteOnExit(); logger.fine(String.format("Setup finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); ImmutableList<DirectoryModifier> modifiers = ImmutableList.of( new PackedResourceTarExpander(working.resolve("expanded"), working), new FileDeDuplicator( Hashing.murmur3_128(), working.resolve("deduplicated"), working)); MergedAndroidData mergedData = resourceProcessor.mergeData( options.mainData, options.dependencyData, resourcesOut, assetsOut, modifiers, null, options.strictMerge); logger.info(String.format("Merging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); writeAar(options.aarOutput, mergedData, options.manifest, options.rtxt, options.classes); logger.info( String.format("Packaging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS))); } catch (IOException | MergingException e) { logger.log(Level.SEVERE, "Error during merging resources", e); System.exit(1); } System.exit(0); }
private void insertFile( Path apkPath, Map<String, String> zip_properties, File insert, String method, Path location) throws AndrolibException, IOException { // ZipFileSystem only writes at .close() // http://mail.openjdk.java.net/pipermail/nio-dev/2012-July/001764.html try (FileSystem fs = FileSystems.newFileSystem(apkPath, null)) { Path root = fs.getPath("/"); // in order to get the path relative to the zip, we strip off the absolute path, minus what we // already have in the zip. thus /var/files/apktool/apk/unknown/folder/file => /folder/file Path dest = fs.getPath(root.toString(), insert.getAbsolutePath().replace(location.toString(), "")); Path newFile = Paths.get(insert.getAbsolutePath()); Files.copy(newFile, dest, StandardCopyOption.REPLACE_EXISTING); fs.close(); } }