/** * 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 + "."); } }
/** * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件 * * @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 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 static Path createDirectory(Path dir) { try { if (!Files.exists(dir)) { return Files.createDirectory(dir); } else { return null; } } catch (Exception ex) { return Exceptions.handle(Path.class, ex); } }
public static Path createChildDirectory(Path parentDir, String childDir) { try { final Path newDir = path(parentDir.toString(), childDir); if (!Files.exists(newDir)) { Files.createDirectory(newDir); } return newDir; } catch (Exception ex) { return Exceptions.handle(Path.class, ex); } }
private void initFrame() { this.setLocationRelativeTo(null); try { if (!Files.exists(saveName)) Files.createFile(saveName); laden(saveName); } catch (IOException e) { e.printStackTrace(); } nUebSchr.setSelected(true); if (!quellListModel.isEmpty()) quellJList.setSelectedIndex(0); if (!zielListModel.isEmpty()) zielJList.setSelectedIndex(0); starteLaufwerkspruefung(); }
/** * Compresses the specified directory to a zip file * * @param dir the directory to compress * @return the compressed file * @throws IOException */ public static Path compress(Path dir) throws IOException { Assert.isTrue(Files.exists(dir), "The directory does not exist: " + dir.toAbsolutePath()); Assert.isTrue(Files.isDirectory(dir), "Should be a directory: " + dir.toAbsolutePath()); Path result = Paths.get(dir.toAbsolutePath() + FileType.DOT_ZIP); try (final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(result.toFile())))) { // out.setMethod(ZipOutputStream.DEFLATED); final byte data[] = new byte[BUFFER]; // get a list of files from current directory Files.walkFileTree( dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs) throws IOException { final File file = path.toFile(); // compress to relative directory, not absolute final String root = StringUtils.substringAfter(file.getParent(), dir.toString()); try (final BufferedInputStream origin = new BufferedInputStream(new FileInputStream(file), BUFFER)) { final ZipEntry entry = new ZipEntry(root + File.separator + path.getFileName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } } return FileVisitResult.CONTINUE; } }); } return result; }
@Override public void run() { logger.debug("Register root " + startDir.toString()); try { registerAll(startDir); } catch (IOException ex) { logger.error(ex.getMessage()); return; } if (isInterrupted()) return; VOSync.debug("Sync local db with drive"); DbPool.goSql( "Synching the local db with drive", "select NAME from FILES", new SqlWorker<Boolean>() { @Override public Boolean go(Connection conn, PreparedStatement stmt) throws SQLException { ResultSet resSet = stmt.executeQuery(); while (resSet.next()) { try { String fileName = resSet.getString(1); Path filePath = FileSystems.getDefault().getPath(startDir.toString(), fileName.substring(1)); if (!filePath.toFile().exists()) { logger.debug( "Deleting file " + fileName + " existing in DB and not present on disk"); api.delete(fileName); MetaHandler.delete(fileName); } } catch (DropboxException ex) { } } resSet.close(); return true; } }); if (isInterrupted()) return; VOSync.debug("Sync storage"); syncStorage(); logger.debug("Start watching"); while (!isInterrupted()) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey " + key.toString() + " not recognized!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { Kind<?> kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); Path relativeDir = startDir.relativize(child); String fileRelPath = "/" + fixPath(relativeDir.toString()); // print out event logger.debug(event.kind().name() + ":" + child + " " + name + " " + key); try { if (Files.exists(child, new LinkOption[] {}) && Files.isHidden(child)) { logger.error( "Skipping hidden file " + child.getFileName()); // skip OS generated catalog files } else { if (event.kind() == ENTRY_CREATE) { if (Files.isRegularFile(child, NOFOLLOW_LINKS)) { // file modified uploadFile(fileRelPath, child); } else if (Files.isDirectory(child, NOFOLLOW_LINKS)) { // directory contents changed registerAll(child); } } else if (event.kind() == ENTRY_DELETE) { logger.debug("Deleting " + fileRelPath); api.delete(fileRelPath); MetaHandler.delete(fileRelPath); logger.debug("Deleted!"); } else if (event.kind() == ENTRY_MODIFY) { if (Files.isRegularFile(child, NOFOLLOW_LINKS)) { // file modified uploadFile(fileRelPath, child); } else if (Files.isDirectory(child, NOFOLLOW_LINKS)) { // directory contents changed // logger.debug("Renewing dir: "+relativeDir.toString()); // TODO update folder date // MetaHandler.setFile(fileRelPath, child, rev); } } } } catch (IOException ex) { ex.printStackTrace(); logger.error(ex.getMessage()); } catch (DropboxException ex) { ex.printStackTrace(); logger.error(ex.getMessage()); } } boolean valid = key.reset(); if (!valid) keys.remove(key); } }
public void cnpStart(Path quellOrdner, Path zielOrdner) { try { DirectoryStream<Path> qstream = Files.newDirectoryStream(quellOrdner); for (Path qfile : qstream) { Path target = Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()); if (abbruch) break; if (Files.isDirectory(qfile) && !Files.exists(target)) { Files.createDirectory(target); textArea.append("Verzeichnis: " + qfile + " wurde erstellt" + System.lineSeparator()); cnpStart( Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()), Paths.get(zielOrdner.toString() + "/" + qfile.getFileName())); } else if (Files.isDirectory(qfile) && Files.exists(target)) { textArea.append("Wechsle in Verzeichnis: " + qfile + System.lineSeparator()); cnpStart( Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()), Paths.get(zielOrdner.toString() + "/" + qfile.getFileName())); } // Wenn die Datei noch nicht existiert else if (!Files.exists(target)) { textArea.append( "Datei " + target.toString() + " wurde erstellt" + System.lineSeparator()); Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING); } // Wenn Datei im Zielverzeichnis schon existiert else if (Files.exists(target)) { if (cAUeSchr) { textArea.append( "Datei " + target.toString() + " wird absolut überschrieben" + System.lineSeparator()); Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING); } else if (cUeSchr) { if (checkAlter( Paths.get(quellOrdner.toString() + "/" + qfile.getFileName()), Paths.get(zielOrdner.toString() + "/" + qfile.getFileName()))) { textArea.append( target.toString() + " wird mit neuer Datei überschrieben" + System.lineSeparator()); Files.copy(qfile, target, StandardCopyOption.REPLACE_EXISTING); } else { textArea.append( target.toString() + " alte Datei bleibt bestehen" + System.lineSeparator()); } } else textArea.append( target.toString() + " alte Datei bleibt bestehen" + System.lineSeparator()); } pbCounter++; progressBar.setValue(pbCounter); } qstream.close(); } catch (IOException e) { e.printStackTrace(); } }