public static void main(String[] args) throws MessagingException, IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) { props.load(in); } List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8")); String from = lines.get(0); String to = lines.get(1); String subject = lines.get(2); StringBuilder builder = new StringBuilder(); for (int i = 3; i < lines.size(); i++) { builder.append(lines.get(i)); builder.append("\n"); } Console console = System.console(); String password = new String(console.readPassword("Password: ")); Session mailSession = Session.getDefaultInstance(props); // mailSession.setDebug(true); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(builder.toString()); Transport tr = mailSession.getTransport(); try { tr.connect(null, password); tr.sendMessage(message, message.getAllRecipients()); } finally { tr.close(); } }
void test(String[] opts, String className) throws Exception { count++; System.err.println("Test " + count + " " + Arrays.asList(opts) + " " + className); Path testSrcDir = Paths.get(System.getProperty("test.src")); Path testClassesDir = Paths.get(System.getProperty("test.classes")); Path classes = Paths.get("classes." + count); classes.createDirectory(); Context ctx = new Context(); PathFileManager fm = new JavacPathFileManager(ctx, true, null); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); List<String> options = new ArrayList<String>(); options.addAll(Arrays.asList(opts)); options.addAll(Arrays.asList("-verbose", "-XDverboseCompilePolicy", "-d", classes.toString())); Iterable<? extends JavaFileObject> compilationUnits = fm.getJavaFileObjects(testSrcDir.resolve(className + ".java")); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); JavaCompiler.CompilationTask t = compiler.getTask(out, fm, null, options, null, compilationUnits); boolean ok = t.call(); System.err.println(sw.toString()); if (!ok) { throw new Exception("compilation failed"); } File expect = new File("classes." + count + "/" + className + ".class"); if (!expect.exists()) throw new Exception("expected file not found: " + expect); long expectedSize = new File(testClassesDir.toString(), className + ".class").length(); long actualSize = expect.length(); if (expectedSize != actualSize) throw new Exception("wrong size found: " + actualSize + "; expected: " + expectedSize); }
public static void main(String[] args) throws IOException { Path path = Paths.get("../alice.txt"); String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); Stream<String> words = Stream.of(contents.split("[\\P{L}]+")); show("words", words); Stream<String> song = Stream.of("gently", "down", "the", "stream"); show("song", song); Stream<String> silence = Stream.empty(); silence = Stream.<String>empty(); // Explicit type specification show("silence", silence); Stream<String> echos = Stream.generate(() -> "Echo"); show("echos", echos); Stream<Double> randoms = Stream.generate(Math::random); show("randoms", randoms); Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE)); show("integers", integers); Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents); show("wordsAnotherWay", wordsAnotherWay); try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) { show("lines", lines); } }
public static void main(String[] args) throws Exception { Path dir = Paths.get(args[0]); Files.walkFileTree( dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { check(dir); if (skip(dir)) return FileVisitResult.SKIP_SIBLINGS; return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { check(file); if (skip(file)) return FileVisitResult.SKIP_SIBLINGS; return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException x) { if (x != null) throw new RuntimeException(x); check(dir); return FileVisitResult.CONTINUE; } }); }
private static FileSystem fileSystem(URI file) { try { return FileSystems.newFileSystem(Paths.get(file.getPath()), null); } catch (IOException e) { throw new RuntimeException(e); } }
public static void main(String args[]) { try { aServer asr = new aServer(); // file channel. FileInputStream is = new FileInputStream(""); is.read(); FileChannel cha = is.getChannel(); ByteBuffer bf = ByteBuffer.allocate(1024); bf.flip(); cha.read(bf); // Path Paths Path pth = Paths.get("", ""); // Files some static operation. Files.newByteChannel(pth); Files.copy(pth, pth); // file attribute, other different class for dos and posix system. BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class); bas.size(); } catch (Exception e) { System.err.println(e); } System.out.println("hello "); }
public static void main(String[] args) throws Exception { boolean followLinks = false; boolean printCycles = false; int i = 0; while (i < (args.length - 1)) { switch (args[i]) { case "-follow": followLinks = true; break; case "-printCycles": printCycles = true; break; default: throw new RuntimeException(args[i] + " not recognized"); } i++; } Path dir = Paths.get(args[i]); Set<FileVisitOption> options = new HashSet<FileVisitOption>(); if (followLinks) options.add(FileVisitOption.FOLLOW_LINKS); final boolean follow = followLinks; final boolean reportCycles = printCycles; Files.walkFileTree( dir, options, Integer.MAX_VALUE, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { System.out.println(dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { System.out.println(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) throw exc; return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (follow && (exc instanceof FileSystemLoopException)) { if (reportCycles) System.out.println(file); return FileVisitResult.CONTINUE; } else { throw exc; } } }); }
public static void main(String[] args) throws IOException { // open file but do not close it. Its existance will be checked by // the calling script. Paths.get(args[0]).newByteChannel(READ, WRITE, DELETE_ON_CLOSE); // check temporary file has been deleted after closing it Path file = File.createTempFile("blah", "tmp").toPath(); file.newByteChannel(READ, WRITE, DELETE_ON_CLOSE).close(); if (file.exists()) throw new RuntimeException("Temporary file was not deleted"); Path dir = TestUtil.createTemporaryDirectory(); try { // check that DELETE_ON_CLOSE fails when file is a sym link if (TestUtil.supportsLinks(dir)) { file = dir.resolve("foo").createFile(); Path link = dir.resolve("link").createSymbolicLink(file); try { link.newByteChannel(READ, WRITE, DELETE_ON_CLOSE); throw new RuntimeException("IOException expected"); } catch (IOException ignore) { } } // check that DELETE_ON_CLOSE works with files created via open // directories DirectoryStream stream = dir.newDirectoryStream(); try { if (stream instanceof SecureDirectoryStream) { SecureDirectoryStream secure = (SecureDirectoryStream) stream; file = Paths.get("foo"); Set<OpenOption> opts = new HashSet<OpenOption>(); opts.add(WRITE); opts.add(DELETE_ON_CLOSE); secure.newByteChannel(file, opts).close(); if (dir.resolve(file).exists()) throw new RuntimeException("File not deleted"); } } finally { stream.close(); } } finally { TestUtil.removeAll(dir); } }
public static void main(String[] args) throws IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get(args[0]))) { props.load(in); } String url = props.remove("url").toString(); String result = doPost(url, props); System.out.println(result); }
private ArrayList<Path> holeLaufwerkeUnix() { ArrayList<Path> laufwerksRoot = new ArrayList<>(); for (FileStore store : FileSystems.getDefault().getFileStores()) { if (store.name().contains("/dev/sd")) { laufwerksRoot.add( Paths.get(store.toString().substring(0, store.toString().indexOf(' ')))); } } return laufwerksRoot; }
private void laden(Path saveName) throws IOException { Properties prop = new Properties(); FileInputStream in = new FileInputStream(saveName.toString()); prop.load(in); for (int i = 0; prop.containsKey(String.format("quellMenu%d", i)); i++) quellListModel.addElement( new ListItem( Paths.get(prop.getProperty(String.format("quellMenu%d", i))), Paths.get(prop.getProperty(String.format("quellMenu%d", i))))); for (int i = 0; prop.containsKey(String.format("zielMenu%d", i)); i++) zielListModel.addElement( new ListItem( Paths.get(prop.getProperty(String.format("zielMenu%d", i))), Paths.get(prop.getProperty(String.format("zielMenu%d", i))))); in.close(); }
@Test @SuppressWarnings("unchecked") public void parse_object() throws IOException { List<Object> members = (List<Object>) parser.parse(resources.sourceFile(Paths.get("_data", "members.yml"))); assertThat(members).hasSize(3); assertThat((Map<String, Object>) members.get(0)) .containsExactly(entry("name", "Tom Preston-Werner"), entry("github", "mojombo")); }
/** * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件 * * @param task * @return "ok" if download success (else return errmessage); */ static String download(DownloadTask task) { if (!openedStatus && show) openStatus(); URL url; HttpURLConnection conn; try { url = new URL(task.getOrigin()); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/" + Math.random()); if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求 conn.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"); // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229; // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800"); conn.setRequestProperty( "Cookie", "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800"); conn.setRequestProperty("Host", "www.imgjav.com"); } Path directory = Paths.get(task.getDest()).getParent(); if (!Files.exists(directory)) Files.createDirectories(directory); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } try (InputStream is = conn.getInputStream(); BufferedInputStream in = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(task.getDest()); OutputStream out = new BufferedOutputStream(fos); ) { int length = conn.getContentLength(); if (length < 1) throw new IOException("length<1"); byte[] binary = new byte[length]; byte[] buff = new byte[65536]; int len; int index = 0; while ((len = in.read(buff)) != -1) { System.arraycopy(buff, 0, binary, index, len); index += len; allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了 task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%"); } out.write(binary); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } return "ok"; }
public void buildUnknownFiles(File appDir, File outFile, Map<String, Object> meta) throws AndrolibException { File file; Path globalPath = Paths.get(appDir.getPath() + File.separatorChar + UNK_DIRNAME); if (meta.containsKey("unknownFiles")) { LOGGER.info("Copying unknown files/dir..."); Map<String, String> files = (Map<String, String>) meta.get("unknownFiles"); try { // set our filesystem options Map<String, String> zip_properties = new HashMap<>(); zip_properties.put("create", "false"); zip_properties.put("encoding", "UTF-8"); // create filesystem Path path = Paths.get(outFile.getAbsolutePath()); // loop through files inside for (Map.Entry<String, String> entry : files.entrySet()) { file = new File(globalPath.toFile(), entry.getKey()); if (file.isFile() && file.exists()) { insertFolder( path, zip_properties, file.getParentFile(), entry.getValue(), globalPath.toAbsolutePath()); insertFile(path, zip_properties, file, entry.getValue(), globalPath.toAbsolutePath()); } } } catch (IOException ex) { throw new AndrolibException(ex); } } }
/** * Makes home folder and the configuration file readable and writable only to the owner. * * @param cs the <tt>ConfigurationService</tt> instance to check for home folder and configuration * file. */ private static void fixPermissions(ConfigurationService cs) { if (!OSUtils.IS_LINUX && !OSUtils.IS_MAC) return; try { // let's check config file and config folder File homeFolder = new File(cs.getScHomeDirLocation(), cs.getScHomeDirName()); Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>() { { add(PosixFilePermission.OWNER_READ); add(PosixFilePermission.OWNER_WRITE); add(PosixFilePermission.OWNER_EXECUTE); } }; Files.setPosixFilePermissions(Paths.get(homeFolder.getAbsolutePath()), perms); String fileName = cs.getConfigurationFilename(); if (fileName != null) { File cf = new File(homeFolder, fileName); if (cf.exists()) { perms = new HashSet<PosixFilePermission>() { { add(PosixFilePermission.OWNER_READ); add(PosixFilePermission.OWNER_WRITE); } }; Files.setPosixFilePermissions(Paths.get(cf.getAbsolutePath()), perms); } } } catch (Throwable t) { logger.error("Error creating c lib instance for fixing file permissions", t); if (t instanceof InterruptedException) Thread.currentThread().interrupt(); else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } }
/** * Gets a connection from the properties specified in the file database.properties * * @return the database connection */ public static Connection getConnection() throws SQLException, IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get("database.properties"))) { props.load(in); } String drivers = props.getProperty("jdbc.drivers"); if (drivers != null) System.setProperty("jdbc.drivers", drivers); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); return DriverManager.getConnection(url, username, password); }
private void parsestories() { try { List<String> lns = Files.readAllLines(Paths.get("datasets/" + name + ".tsv"), Charset.defaultCharset()); for (String ln : lns) stories.add(Story.fromtext(ln)); } catch (IOException e) { System.out.println("Error reading dataset."); System.exit(1); } }
@Test public void extension() { assertThat(Resources.extension(Paths.get("file.txt"))).isEqualTo(".txt"); assertThat(Resources.extension(Paths.get("file.css.map"))).isEqualTo(".map"); assertThat(Resources.extension(Paths.get(".dotfile.ext"))).isEqualTo(".ext"); assertThat(Resources.extension(Paths.get("file"))).isEmpty(); assertThat(Resources.extension(Paths.get(".dotfile"))).isEmpty(); assertThat(Resources.extension(Paths.get("."))).isEmpty(); }
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(); } }
private int getNumberOfItems(Path quellOrdner) { int retValue = 0; try { DirectoryStream<Path> qstream = Files.newDirectoryStream(quellOrdner); for (Path qfile : qstream) { if (Files.isDirectory(qfile)) { getNumberOfItems(Paths.get(quellOrdner.toString() + "/" + qfile.getFileName())); } i++; } qstream.close(); } catch (IOException e) { e.printStackTrace(); } retValue = i; return retValue; }
private void getCompileClasspath( List<String> list, Set<Artifact> cutoff, DependentLoaderImplementation depLoader) { if (!cutoff.contains(depLoader.artifact)) { cutoff.add(depLoader.artifact); DependentLoaderImplementation depLoaderImpl = enshureJarLoaded(depLoader.artifact); for (URL url : depLoader.getURLs()) { try { String path = Paths.get(url.toURI()).toFile().getAbsolutePath(); if (!list.contains(path)) { list.add(path); } } catch (Exception e) { } } for (DependentLoaderImplementation dep : depLoaderImpl.dependencies) { getCompileClasspath(list, cutoff, dep); } } }
private static void extractAndLoadNativeLibs() throws IOException { Path target = Paths.get(ioTmpDir, "/tklib"); if (!target.toFile().exists()) { Files.createDirectories(target); } final boolean windows = System.getProperty("os.name").equalsIgnoreCase("windows"); String fileExtension = windows ? "dll" : "so"; String prefix = windows ? "" : "lib"; String libPattern = fileExtension.equals("dll") ? "-windows" : "-linux" + "-x86"; if (System.getProperty("sun.arch.data.model").equals("64")) { libPattern += "_64"; } libPattern += "." + fileExtension; // System.err.println(libPattern); System.setProperty("java.library.path", target.toString()); // System.err.println(System.getProperty("java.library.path")); extractAndLoadNativeLib(prefix + "JCudaDriver" + libPattern, target); extractAndLoadNativeLib(prefix + "JCudaRuntime" + libPattern, target); extractAndLoadNativeLib(prefix + "JCurand" + libPattern, target); }
@BeforeClass public static void findDependencies() throws Exception { Path path = Paths.get("target/classes"); Archive archive = new Archive(path, ClassFileReader.newInstance(path)) {}; Finder finder = Dependencies.getClassDependencyFinder(); archive .reader() .getClassFiles() .forEach( classFile -> StreamSupport.stream(finder.findDependencies(classFile).spliterator(), false) .filter(dependency -> !isAnnotation(dependency)) .filter(dependency -> !self(dependency)) .forEach( dependency -> packageDependencies .computeIfAbsent( dependency.getOrigin().getPackageName(), key -> new TreeSet<>()) .add(dependency.getTarget().getPackageName()))); }
// void compileKernelsPtx() static void compileKernelsPtx() throws IOException { if (!new File(ioTmpDir, PHEROMONES_CU + ".ptx").exists()) { // TODO externalize try (InputStream is = CudaEngine.class.getResourceAsStream( "/turtlekit/cuda/kernels/" + PHEROMONES_CU + ".cu")) { final Path path = Paths.get(ioTmpDir, PHEROMONES_CU + ".cu"); try { Files.copy(is, path); } catch (FileAlreadyExistsException e) { } System.err.println("--------------- Compiling ptx ----------------------"); KernelLauncher.create( path.toString(), Kernel.DIFFUSION_TO_TMP.name(), false, "--use_fast_math", "--prec-div=false"); // ,"--gpu-architecture=sm_20"); } catch (IOException e) { throw e; } } }
private List<ClassData> collectClasses(List<URI> uris) { List<ClassData> found = new ArrayList<>(); for (URI uri : uris) { if (uri.getPath().endsWith(".jar")) { fileSystem(uri) .getRootDirectories() .forEach( root -> walk(root) .filter(f -> f.toString().endsWith(".class")) .map(ClassData::new) .forEach(found::add)); } else { walk(Paths.get(uri)) .filter(f -> f.toString().endsWith(".class")) .map(ClassData::new) .forEach(found::add); } } return found; }
public static void main(String args[]) throws IOException { try { Scanner in = args.length == 0 ? new Scanner(System.in) : new Scanner(Paths.get(args[0])); try (Connection conn = getConnection()) { Statement stat = conn.createStatement(); while (true) { if (args.length == 0) System.out.println("Enter command or EXIT to exit:"); if (!in.hasNextLine()) return; String line = in.nextLine(); if (line.equalsIgnoreCase("EXIT")) return; if (line.trim().endsWith(";")) // remove trailing semicolon { line = line.trim(); line = line.substring(0, line.length() - 1); } try { boolean isResult = stat.execute(line); if (isResult) { ResultSet rs = stat.getResultSet(); showResultSet(rs); } else { int updateCount = stat.getUpdateCount(); System.out.println(updateCount + " rows updated"); } } catch (SQLException ex) { for (Throwable e : ex) e.printStackTrace(); } } } } catch (SQLException e) { for (Throwable t : e) t.printStackTrace(); } }
private static void extractAndLoadNativeLib(String nativeLibName, Path target) { // System.err.println("loading "+nativeLibName); final Path path = Paths.get(target.toString(), nativeLibName); if (!path.toFile().exists()) { try (InputStream is = CudaEngine.class .getClassLoader() .getResourceAsStream("/lib/" + nativeLibName)) { // TODO TK property for lib dir Files.copy(is, path); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { // TODO find a way to do it instead of eclipse final Path eclipsePath = FileSystems.getDefault().getPath("lib", nativeLibName); try { Files.copy(eclipsePath, path); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } System.load(path.toString()); // System.load(nativeLibName); }
private static Path getSourcePath() { return Paths.get("src/test/java/"); }
public PalindromeTest() { ArrayList<String> words = new ArrayList<String>(); ArrayList<String> palis; try { for (String line : Files.readAllLines(Paths.get("com/jsanders/web2"))) { words.add(line); } } catch (IOException ex) { System.out.println("IO error"); System.exit(1); } palis = Palindrome.palindromes(words); assertEquals(palis.size(), 161, 0.01); int shortest = Word.shortestLength(words); assertEquals(shortest, 1, 0.01); int longest = Word.longestLength(words); assertEquals(longest, 24, 0.01); ArrayList<String> shortestWords = Word.shortestWords(words); assertEquals(shortestWords.size(), 52, 0.01); ArrayList<String> longestWords = Word.longestWords(words); assertEquals(longestWords.size(), 5, 0.01); int totalWords = Word.totalWords(words); double avgLen = Word.averageLength(words); assertEquals(totalWords, 235886, 0.01); assertEquals(avgLen, 9.56, 0.01); ArrayList<Double> letterFreq = Word.letterFrequency(words); assertEquals(letterFreq.get(0), 0.087, 0.01); double properFreq = Word.properFrequency(words); assertEquals(properFreq, 0.106, 0.01); ArrayList<Integer> startFreq = Word.startFrequency(words); assertEquals(startFreq.get(0), 17096, 0.01); ArrayList<String> sameStartEnd = Word.startEndWords(words); assertEquals(sameStartEnd.size(), 11505, 0.01); try { PrintWriter f = new PrintWriter("short.txt"); for (String w : shortestWords) f.println(w); f.close(); f = new PrintWriter("long.txt"); for (String w : longestWords) f.println(w); f.close(); f = new PrintWriter("same.txt"); for (String w : sameStartEnd) f.println(w); f.close(); f = new PrintWriter("statistics.txt"); f.println("avg word len: " + avgLen); f.println("freq of letters: " + letterFreq); f.println("freq of proper nouns/names: " + properFreq); f.println("words that start with each letter:: " + startFreq); f.close(); } catch (IOException ex) { System.out.println("IO error"); System.exit(1); } }
/** @throws IOException */ public static void start() throws IOException { // флаг для рекурсивного просмотра каталогов Path dir = Paths.get(IN_PATH); new WatchDir(dir).processEvents(); }