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(); } }
private List<Path> getPathsFromFile(String file, List<Path> filesToCombine) throws IOException { Path filePath = Paths.get(file); File fileLister = filePath.toFile(); BufferedReader br = new BufferedReader(new FileReader(fileLister)); String line; PathMatcher matcher; Finder finder = new Finder(); String parentFolder; Path filePathToCombine; while ((line = br.readLine()) != null) { if (line.isEmpty()) { continue; } parentFolder = ""; filePathToCombine = Paths.get(line); if (filePathToCombine.getParent() != null) { parentFolder = filePathToCombine.getParent().toString(); } matcher = FileSystems.getDefault() .getPathMatcher("glob:" + filePathToCombine.getFileName().toString()); finder.setMatcher(matcher); Files.walkFileTree( Paths.get(fileLister.getAbsoluteFile().getParent() + parentFolder), finder); } filesToCombine.addAll(finder.getMatchPath()); return filesToCombine; }
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 createDirectories() { final String[] dirs = { Paths.getHomeDirectory(), Paths.getLogsDirectory(), Paths.getCacheDirectory(), Paths.getSettingsDirectory(), Paths.getScriptsDirectory(), Paths.getScriptsSourcesDirectory(), Paths.getScriptsPrecompiledDirectory(), Paths.getScriptsNetworkDirectory(), }; for (final String name : dirs) { final File dir = new File(name); if (!dir.isDirectory()) { dir.mkdirs(); } } if (Configuration.getCurrentOperatingSystem() == Configuration.OperatingSystem.WINDOWS) { try { Runtime.getRuntime() .exec( "attrib +H \"" + new File(Paths.getScriptsNetworkDirectory()).getAbsolutePath() + "\""); } catch (final IOException ignored) { } } }
public static void main(String[] args) throws IOException { System.out.println("Input Stream:"); long start = System.currentTimeMillis(); Path filename = Paths.get(args[0]); long crcValue = checksumInputStream(filename); long end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); System.out.println("Buffered Input Stream:"); start = System.currentTimeMillis(); crcValue = checksumBufferedInputStream(filename); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); System.out.println("Random Access File:"); start = System.currentTimeMillis(); crcValue = checksumRandomAccessFile(filename); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); System.out.println("Mapped File:"); start = System.currentTimeMillis(); crcValue = checksumMappedFile(filename); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); }
/** * Checks if a given file exists and, if not, create it by copying a default template from * resources; used to create default conf files. * * @param file The path of the file that needs to exist * @param template The path of the template for the file */ public static void ensureFileExists(final String file, final String template) { if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) { if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one."); InputStream stream = Meta.class.getResourceAsStream(template); if (stream == null) { printDebug( "[ WARNING ] template for " + template + " not found. Won't create a default " + file + "."); } else { int readBytes; byte[] buffer = new byte[4096]; try (OutputStream outStream = new FileOutputStream(new File(file))) { while ((readBytes = stream.read(buffer)) > 0) { outStream.write(buffer, 0, readBytes); } if (Debug.on) printDebug("[Meta] created default file " + file + " from " + template + "."); } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException ignore) { } } } } else { if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + "."); } }
private void compareBinaryFolder(String path, boolean res) throws BrutException, IOException { String tmp = ""; if (res) { tmp = File.separatorChar + "res" + File.separatorChar; } Files.walkFileTree( Paths.get(sTestOrigDir.toPath() + tmp + path), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // hacky fix - load test by changing name of control File control = file.toFile(); File test = new File(file.toString().replace("testapp-orig", "testapp-new")); if (test.isFile()) { if (control.hashCode() != test.hashCode()) { sResult = false; return FileVisitResult.TERMINATE; } } else { sResult = false; return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } }); }
/** * Removes any <code>"."</code> and <code>".."</code> directories from the * path wherever possible. * * @param file The file instance which's path is to be normalized. * @return <code>file</code> if it was already in normalized form. Otherwise, an object which's * runtime class is guaranteed to be <code>java.io.File</code>. */ public static java.io.File normalize(final java.io.File file) { final String path = file.getPath(); final String newPath = Paths.normalize(path, File.separatorChar); return newPath != path // mind contract of Paths.normalize! ? new java.io.File(newPath) : file; }
public void processInDirectory() { // // распакуем все файлы из каталага in // final int BUFFER_SIZE = 4096; SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); final String sessionDate = df.format(new Date()); // // ищем файлы с ответом logger.info("Обрабатываем входной каталог " + ABS_INPUT_DIR); try { File[] directoryList = (new File(ABS_INPUT_DIR)) .listFiles( pathname -> !pathname.isDirectory() && pathname.getName().endsWith(".zip")); // // распаковываем каждый zip // for (File curFile : directoryList) { logger.info("Распаковываем " + curFile.getName()); // // открываем архив // FileInputStream fis = new FileInputStream(curFile); ZipInputStream zis = new ZipInputStream(fis); ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { // // пропускаем директории, т.к. их быть не должно // if (zipEntry.isDirectory()) continue; // // из архива извлекаем только xml !!! // if (zipEntry.getName().endsWith(".xml")) { File unzippedFile = new File(ABS_INPUT_DIR + "/" + zipEntry.getName()); logger.info("Извлекаем файл " + zipEntry.getName()); FileOutputStream fos = new FileOutputStream(unzippedFile); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count = zis.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); } zis.closeEntry(); } zis.close(); fis.close(); Files.move( curFile.toPath(), Paths.get(ABS_ARCH_IN_DIR + "/" + sessionDate + "-" + curFile.getName())); } } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } logger.info("Обработан входной каталог " + ABS_INPUT_DIR); }
@Override public void run(String... args) throws Exception { CommandLine line = this.commandLineParser.parse(this.options, args); String[] remainingArgs = line.getArgs(); if (remainingArgs.length < 3 && !line.hasOption("file") || remainingArgs.length < 1 && line.hasOption("file")) { helpFormatter.printHelp("xmergel [OPTION] [file1 file2 ...] [result_file]", this.options); System.exit(1); } if (line.hasOption("debug")) { this.isDebug = true; } List<Path> filesToCombine = this.getPathsFromArgs(remainingArgs); if (line.hasOption("file")) { System.out.println("Finding files..."); filesToCombine = this.getPathsFromFile(line.getOptionValue("file"), filesToCombine); } String output = remainingArgs[remainingArgs.length - 1]; System.out.println("Merging files..."); try { this.xmergel.setResultFile(output); this.xmergel.combine(filesToCombine); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); if (this.isDebug) { e.printStackTrace(); } System.exit(1); } File fileOutput = Paths.get(output).toFile(); System.out.println("Files have been merged in '" + fileOutput.getAbsolutePath() + "'."); }
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[]) { 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 "); }
static { String tmp = Meta.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // Strip the leading slash if on windows if (tmp.matches("^/[A-Z]:/.*")) { tmp = tmp.substring(1); } cwd = Paths.get(tmp); }
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 String getAccountsFile() { final String path; if (Configuration.getCurrentOperatingSystem() == OperatingSystem.WINDOWS) { path = System.getenv("APPDATA") + File.separator + Configuration.NAME + "_Accounts.ini"; } else { path = Paths.getUnixHome() + File.separator + "." + Configuration.NAME_LOWERCASE + "acct"; } return path; }
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); }
public int countFiles(String root) { CountFile fileProcessor = new CountFile(); try { Files.walkFileTree(Paths.get(root), fileProcessor); } catch (IOException e) { e.printStackTrace(); } return fileProcessor.getTotal(); }
@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")); }
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(); }
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; }
/** * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件 * * @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 static void write(String fullyNamedPath, String... lines) { Path file = Paths.get(fullyNamedPath); try { Files.write( file, Arrays.asList(lines), Charset.forName("UTF-8"), StandardOpenOption.CREATE_NEW); } catch (IOException ioEx) { // TODO: Report to front-end if (LOGGER.isDebugEnabled()) { LOGGER.debug("", ioEx); } } }
public static String getHomeDirectory() { final String env = System.getenv(Configuration.NAME.toUpperCase() + "_HOME"); if (env == null || env.isEmpty()) { return (Configuration.getCurrentOperatingSystem() == OperatingSystem.WINDOWS ? FileSystemView.getFileSystemView().getDefaultDirectory().getAbsolutePath() : Paths.getUnixHome()) + File.separator + Configuration.NAME; } else { return env; } }
public static boolean write(String fullyNamedPath, String content) { Path file = Paths.get(fullyNamedPath); try { Files.deleteIfExists(file); Files.write( file, Arrays.asList(content), Charset.forName("UTF-8"), StandardOpenOption.CREATE_NEW); } catch (IOException ioEx) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("", ioEx); } } return Files.exists(file, LinkOption.NOFOLLOW_LINKS); }
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; } }
public static Path path(String location) { if (!location.startsWith(CLASSPATH_SCHEMA + ":")) { return Paths.get(location); } else { String path = StringScanner.split(location, ':')[1]; final List<Path> resources = Classpaths.resources(IO.class, path); Path result = Lists.idx(resources, 0); if (result == null) { return path(path); } return result; } }
/** * 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); } }
public IdedClient() { boolean ok = false; try { ProcessBuilder builder = new ProcessBuilder(); Paths paths = new Paths(); builder.environment().put("RUST_HOME", paths.getRustHome().getPath()); builder.command(paths.getIded().getPath()); process = builder.start(); stdoutReader = new Thread(new StdoutReader(process.getInputStream())); stderrReader = new Thread(new StderrReader(process.getErrorStream())); stdoutReader.start(); stderrReader.start(); ok = true; } catch (IOException e) { throw new RuntimeException(e); } finally { if (!ok) { close(); } } }