Example #1
0
 /**
  * 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 + ".");
   }
 }
Example #2
0
File: IO.java Project: nremond/boon
  public static void write(OutputStream out, String content) {

    try (OutputStream o = out) {
      o.write(content.getBytes(DEFAULT_CHARSET));
    } catch (Exception ex) {
      Exceptions.handle(ex);
    }
  }
Example #3
0
File: IO.java Project: nremond/boon
  public static void write(OutputStream out, String content, Charset charset) {

    try (OutputStream o = out) {
      o.write(content.getBytes(charset));
    } catch (Exception ex) {
      Exceptions.handle(ex);
    }
  }
Example #4
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @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";
  }
Example #5
0
 void copy(InputStream in, File dest) throws IOException {
   dest.getParentFile().mkdirs();
   OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
   try {
     byte[] data = new byte[8192];
     int n;
     while ((n = in.read(data, 0, data.length)) > 0) out.write(data, 0, n);
   } finally {
     out.close();
     in.close();
   }
 }
Example #6
0
 // create file of random size in given directory
 static Path createSourceFile(Path dir) throws IOException {
   String name = "source" + Integer.toString(rand.nextInt());
   Path file = dir.resolve(name);
   createFile(file);
   byte[] bytes = new byte[rand.nextInt(128 * 1024)];
   rand.nextBytes(bytes);
   try (OutputStream out = newOutputStream(file)) {
     out.write(bytes);
   }
   randomizeAttributes(file);
   return file;
 }
Example #7
0
  public void run() {
    try {

      sc = new Socket();
      InetSocketAddress isa = new InetSocketAddress("localhost", 9999);
      sc.connect(isa);
      OutputStream ost = sc.getOutputStream();

      for (int i = 0; i < 10; ++i) {
        String str = "client interation " + (new Integer(i)).toString();
        ost.write(str.getBytes());
        ost.flush();
        System.out.println("Client at " + (new Integer(i)).toString());
        sleep(1000);
      }
    } catch (Exception e) {
    }
  }
Example #8
0
  /** Simple test of each of the standard events */
  static void testEvents(Path dir) throws IOException {
    System.out.println("-- Standard Events --");

    FileSystem fs = FileSystems.getDefault();
    Path name = fs.getPath("foo");

    try (WatchService watcher = fs.newWatchService()) {
      // --- ENTRY_CREATE ---

      // register for event
      System.out.format("register %s for ENTRY_CREATE\n", dir);
      WatchKey myKey = dir.register(watcher, new WatchEvent.Kind<?>[] {ENTRY_CREATE});
      checkKey(myKey, dir);

      // create file
      Path file = dir.resolve("foo");
      System.out.format("create %s\n", file);
      Files.createFile(file);

      // remove key and check that we got the ENTRY_CREATE event
      takeExpectedKey(watcher, myKey);
      checkExpectedEvent(myKey.pollEvents(), StandardWatchEventKinds.ENTRY_CREATE, name);

      System.out.println("reset key");
      if (!myKey.reset()) throw new RuntimeException("key has been cancalled");

      System.out.println("OKAY");

      // --- ENTRY_DELETE ---

      System.out.format("register %s for ENTRY_DELETE\n", dir);
      WatchKey deleteKey = dir.register(watcher, new WatchEvent.Kind<?>[] {ENTRY_DELETE});
      if (deleteKey != myKey) throw new RuntimeException("register did not return existing key");
      checkKey(deleteKey, dir);

      System.out.format("delete %s\n", file);
      Files.delete(file);
      takeExpectedKey(watcher, myKey);
      checkExpectedEvent(myKey.pollEvents(), StandardWatchEventKinds.ENTRY_DELETE, name);

      System.out.println("reset key");
      if (!myKey.reset()) throw new RuntimeException("key has been cancalled");

      System.out.println("OKAY");

      // create the file for the next test
      Files.createFile(file);

      // --- ENTRY_MODIFY ---

      System.out.format("register %s for ENTRY_MODIFY\n", dir);
      WatchKey newKey = dir.register(watcher, new WatchEvent.Kind<?>[] {ENTRY_MODIFY});
      if (newKey != myKey) throw new RuntimeException("register did not return existing key");
      checkKey(newKey, dir);

      System.out.format("update: %s\n", file);
      try (OutputStream out = Files.newOutputStream(file, StandardOpenOption.APPEND)) {
        out.write("I am a small file".getBytes("UTF-8"));
      }

      // remove key and check that we got the ENTRY_MODIFY event
      takeExpectedKey(watcher, myKey);
      checkExpectedEvent(myKey.pollEvents(), StandardWatchEventKinds.ENTRY_MODIFY, name);
      System.out.println("OKAY");

      // done
      Files.delete(file);
    }
  }