Beispiel #1
1
  @Override
  public void run() {

    // see
    // http://stackoverflow.com/questions/24312147/bufferedwriter-printwriter-outputstreamwriter-dont-flush-buffer-until-close
    BufferedOutputStream bos = null;
    try {
      BufferedInputStream bis = new BufferedInputStream(is);
      bos = new BufferedOutputStream(os);
      byte[] buffer = new byte[32]; // Adjust if you want
      int bytesRead;
      while ((bytesRead = bis.read(buffer)) != -1 && !stop) {
        bos.write(buffer, 0, bytesRead);
        bos.flush();
        bytesPumped += bytesRead;
      }
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } finally {
      try {
        if (bos != null) bos.close();
      } catch (IOException ioe2) {
        // ignore
      }
    }
  }
    /** Writes the chunks to a file as a contiguous stream. Useful for debugging. */
    public void saveToFile(File file) {
      Log.d(TAG, "saving chunk data to file " + file);
      FileOutputStream fos = null;
      BufferedOutputStream bos = null;

      try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        fos = null; // closing bos will also close fos

        int numChunks = getNumChunks();
        for (int i = 0; i < numChunks; i++) {
          byte[] chunk = mChunks.get(i);
          bos.write(chunk);
        }
      } catch (IOException ioe) {
        throw new RuntimeException(ioe);
      } finally {
        try {
          if (bos != null) {
            bos.close();
          }
          if (fos != null) {
            fos.close();
          }
        } catch (IOException ioe) {
          throw new RuntimeException(ioe);
        }
      }
    }
  /**
   * @param url
   * @param request
   * @param resContentHeaders
   * @param timeout
   * @return
   * @throws java.lang.Exception
   * @deprecated As of proxy release 1.0.10, replaced by {@link #sendRequestoverHTTPS( boolean
   *     isBusReq, URL url, String request, Map resContentHeaders, int timeout)}
   */
  public static String sendRequestOverHTTPS(
      URL url, String request, Map resContentHeaders, int timeout) throws Exception {

    // Set up buffers and streams
    StringBuffer buffy = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
      HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      // this makes the assumption that all https requests are going to the bus using UTF-8 encoding
      String encodedString =
          URLEncoder.encode(request, FastHttpClientConstants.HTTP_REQUEST_ENCODING);
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      out.write(FastHttpClientConstants.HTTP_REQUEST_POST_KEY.getBytes());
      out.write(encodedString.getBytes());
      out.flush();

      // Response
      // this mangles 2 or more byte characters
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      buffy = new StringBuffer(INPUT_BUFFER_LEN);
      int ch = 0;
      while ((ch = in.read()) > -1) {
        buffy.append((char) ch);
      }

      populateHTTPSHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return buffy == null ? null : buffy.toString();
  }
Beispiel #4
1
 // load the native library unowinreg.dll
 // FIXME: drop dependency on unowinreg.dll and use com.ice.jni.registry instead
 static {
   try {
     ClassLoader cl = WinRegKey.class.getClassLoader();
     InputStream is = cl.getResourceAsStream("win/unowinreg.dll");
     if (is != null) {
       // generate a temporary name for lib file and write to temp
       // location
       BufferedInputStream istream = new BufferedInputStream(is);
       File libfile = File.createTempFile("unowinreg", ".dll");
       libfile.deleteOnExit(); // ensure deletion
       BufferedOutputStream ostream = new BufferedOutputStream(new FileOutputStream(libfile));
       int bsize = 2048;
       int n = 0;
       byte[] buffer = new byte[bsize];
       while ((n = istream.read(buffer, 0, bsize)) != -1) {
         ostream.write(buffer, 0, n);
       }
       istream.close();
       ostream.close();
       // load library
       System.load(libfile.getPath());
     } else {
       // If the library cannot be found as a class loader resource,
       // try the global System.loadLibrary(). The JVM will look for
       // it in the java.library.path.
       System.loadLibrary("unowinreg");
     }
   } catch (java.lang.Exception e) {
     System.err.println(WinRegKey.class.getName() + " loading of native library failed!" + e);
   }
 }
  /** Upload single file using Spring Controller */
  @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
  public @ResponseBody String uploadFileHandler(
      @RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();

        // Creating the directory to store file
        String rootPath = System.getProperty("catalina.home");
        File dir = new File(rootPath + File.separator + "tmpFiles");
        System.out.println("Upload path " + dir);
        if (!dir.exists()) dir.mkdirs();

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

        logger.info("Server File Location=" + serverFile.getAbsolutePath());

        return "You successfully uploaded file=" + name;
      } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    } else {
      return "You failed to upload " + name + " because the file was empty.";
    }
  }
Beispiel #6
1
  public void extract(File in, File out) throws IOException {
    if (in.length() < this.sectionOffset + this.sectionSize) {
      throw new IOException("File doesn't match with sectionOffset/Size!");
    } else if (!in.exists() || !in.isFile()) {
      throw new IOException("Can't access input file!");
    } else if (out.exists()) {
      throw new IOException("Output file already exists!");
    }

    FileInputStream fis = new FileInputStream(in);
    BufferedInputStream bis = new BufferedInputStream(fis);
    FileOutputStream fos = new FileOutputStream(out);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    // If section isn't empty
    if (sectionSize > 0) {
      bis.skip(this.sectionOffset);
      for (int i = 0; i < this.sectionSize; i++) {
        bos.write(bis.read());
      }
    }

    bos.close();
    bis.close();
  }
Beispiel #7
0
  /**
   * Execute the given command and optionally wait and dump the results to standard out
   *
   * @param args command and arguments
   * @param wait true =wait for either completion or timeout time and dump output, false don't wait
   *     and ignore the output.
   * @exception Exception
   */
  private static void execCmdDumpResults(String[] args, boolean wait) throws Exception {
    // We need the process inputstream and errorstream
    ProcessStreamResult prout = null;
    ProcessStreamResult prerr = null;

    System.out.flush();
    bos.flush();

    BufferedOutputStream _bos = bos;
    if (!wait) {
      // not interested in the output, don't expect a huge amount.
      // information will just be written to the byte array in
      // memory and never used.
      _bos = new BufferedOutputStream(new ByteArrayOutputStream());
    }
    // Start a process to run the command
    Process pr = execCmd(args);

    // Note, the timeout handling will only come into effect when we make
    // the Wait() call on ProcessStreamResult.
    prout = new ProcessStreamResult(pr.getInputStream(), _bos, timeoutMinutes);
    prerr = new ProcessStreamResult(pr.getErrorStream(), _bos, timeoutMinutes);

    if (!wait) return;

    // wait until all the results have been processed or if we timed out
    prout.Wait();
    prerr.Wait();
    _bos.flush();
    System.out.flush();
  }
Beispiel #8
0
  /**
   * 拷贝文件
   *
   * @param fileDir
   * @param fileName
   * @param buffer
   * @return
   */
  public static int copyFile(String fileDir, String fileName, byte[] buffer) {
    if (buffer == null) {
      return -2;
    }

    try {
      File file = new File(fileDir);
      if (!file.exists()) {
        file.mkdirs();
      }
      File resultFile = new File(file, fileName);
      if (!resultFile.exists()) {
        resultFile.createNewFile();
      }
      BufferedOutputStream bufferedOutputStream =
          new BufferedOutputStream(new FileOutputStream(resultFile, true));
      bufferedOutputStream.write(buffer);
      bufferedOutputStream.flush();
      bufferedOutputStream.close();
      return 0;

    } catch (Exception e) {
    }
    return -1;
  }
Beispiel #9
0
 // ============================================================
 // <T>将指定内容存储到一个指定的文件中。</T>
 // <P>如果指定文件的目录不存在,则自动创建目录。</P>
 //
 // @param fileName 文件名称
 // ============================================================
 public void saveToFile(String fileName) {
   // 建立目录
   fileName = RFile.formatFileName(fileName);
   int find = fileName.lastIndexOf(File.separator);
   if (-1 != find) {
     String path = fileName.substring(0, find);
     File directory = new File(path);
     if (!directory.isDirectory()) {
       directory.mkdirs();
     }
   }
   // 存储文件
   BufferedOutputStream outputStream = null;
   try {
     File file = new File(fileName);
     outputStream = new BufferedOutputStream(new FileOutputStream(file));
     if (_memory != null) {
       outputStream.write(_memory, 0, _length);
     }
   } catch (Exception e) {
     throw new FFatalError(e, "Save file failure. (file_name={1})", fileName);
   } finally {
     if (outputStream != null) {
       try {
         outputStream.close();
       } catch (Exception e) {
         throw new FFatalError(e, "Close file failure. (file_name={0})", fileName);
       }
     }
   }
 }
Beispiel #10
0
 private void generaReporte(String tipo, List<Entrada> entradas, HttpServletResponse response)
     throws JRException, IOException {
   log.debug("Generando reporte {}", tipo);
   byte[] archivo = null;
   switch (tipo) {
     case "PDF":
       archivo =
           reporteUtil.generaPdf(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("application/pdf");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.pdf");
       break;
     case "CSV":
       archivo =
           reporteUtil.generaCsv(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("text/csv");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.csv");
       break;
     case "XLS":
       archivo =
           reporteUtil.generaXls(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("application/vnd.ms-excel");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.xls");
   }
   if (archivo != null) {
     response.setContentLength(archivo.length);
     try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
       bos.write(archivo);
       bos.flush();
     }
   }
 }
    private void moveImage(String source, String dest) {
      try {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        File src = new File(source);
        File dst = new File(dest);

        try {
          bis = new BufferedInputStream(new FileInputStream(src), 8096);
          bos = new BufferedOutputStream(new FileOutputStream(dst), 8096);

          byte[] buf = new byte[8096];
          int len = 0;

          while ((len = bis.read(buf)) != -1) {
            bos.write(buf, 0, len);
          }

        } finally {
          if (bis != null) {
            bis.close();
          }

          if (bos != null) {
            bos.close();
          }
        }
        src.delete();

      } catch (IOException e) {
        Log.e(TAG, "Unable to move file: " + e.getMessage(), e);
      }
    }
Beispiel #12
0
  // 复制文件
  public static void copyFile(String sourcePath, String toPath) {
    File sourceFile = new File(sourcePath);
    File targetFile = new File(toPath);
    createDipPath(toPath);
    try {
      BufferedInputStream inBuff = null;
      BufferedOutputStream outBuff = null;
      try {
        // 新建文件输入流并对它进行缓冲
        inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

        // 新建文件输出流并对它进行缓冲
        outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

        // 缓冲数组
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1) {
          outBuff.write(b, 0, len);
        }
        // 刷新此缓冲的输出流
        outBuff.flush();
      } finally {
        // 关闭流
        if (inBuff != null) inBuff.close();
        if (outBuff != null) outBuff.close();
      }
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Beispiel #13
0
  public void run() {
    try {
      for (Slice.FileData data = slice.readNextFile(); data != null; data = slice.readNextFile()) {
        FileList.FileLocation file = data.file;

        ByteArrayInputStream in = new ByteArrayInputStream(data.data);
        decoder.SetDecoderProperties(data.props);

        String fileName = destpath + "/" + file.fileName;
        File f = new File(fileName);
        f.getParentFile().mkdirs();

        // check if we need to undo the tranformation on x86 executables
        if ((file.fileName.contains(".exe")
            || file.fileName.contains(".dll"))) { // TODO there is an attribute for this
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          decoder.Code(in, out, file.originalSize);
          byte[] decompressedData = out.toByteArray();
          Util.transformCallInstructions(decompressedData);
          BufferedOutputStream outfile = new BufferedOutputStream(new FileOutputStream(f));
          outfile.write(decompressedData);
          outfile.close();
        } else {
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
          decoder.Code(in, out, file.originalSize);
          out.close();
        }
        f.setLastModified(file.mtime.getTime());
        ui.increaseProgress();
      }
    } catch (Exception e) {
      ui.showError(e.getLocalizedMessage());
      e.printStackTrace();
    }
  }
Beispiel #14
0
 @Override
 public void provideResourceTo(Consumer<? super OutputStream> consumer) {
   try {
     OutputStream stream = new HUPReopeningFileOutputStream(file);
     try {
       BufferedOutputStream bufferedStream = new BufferedOutputStream(stream);
       try {
         consumer.accept(bufferedStream);
       } finally {
         try {
           bufferedStream.close();
         } catch (Exception ex) {
           Logger.getLogger(LogFileStreamProvider.class.getName()).log(Level.SEVERE, null, ex);
         }
       }
     } finally {
       try {
         stream.close();
       } catch (Exception ex) {
         Logger.getLogger(LogFileStreamProvider.class.getName()).log(Level.SEVERE, null, ex);
       }
     }
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   }
 }
Beispiel #15
0
  public static boolean copyFile(InputStream is, File dest) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {
      bis = new BufferedInputStream(is);
      bos = new BufferedOutputStream(new FileOutputStream(dest, false));

      byte[] buf = new byte[1024];
      bis.read(buf);

      do {
        bos.write(buf);
      } while (bis.read(buf) != -1);
    } catch (IOException e) {
      return false;
    } finally {
      try {
        if (bis != null) bis.close();
        if (bos != null) bos.close();
      } catch (IOException e) {
        return false;
      }
    }

    return true;
  }
  public static void xs3_upload_by_url(URL xs3_url, String file_path) throws IOException {

    BufferedInputStream xs3_instream = null;
    BufferedOutputStream xs3_outstream = null;
    try {
      HttpURLConnection http_conn = (HttpURLConnection) xs3_url.openConnection();
      http_conn.setDoOutput(true);
      http_conn.setRequestMethod("PUT");

      http_conn.setRequestProperty("Content-Type", "image/jpeg");
      http_conn.setRequestProperty("x-amz-acl", "public-read");

      xs3_outstream = new BufferedOutputStream(http_conn.getOutputStream());
      xs3_instream = new BufferedInputStream(new FileInputStream(new File(file_path)));

      byte[] buffer = new byte[1024];
      int xs3_offset = 0;
      while ((xs3_offset = xs3_instream.read(buffer)) != -1) {
        xs3_outstream.write(buffer, 0, xs3_offset);
        xs3_outstream.flush();
      }

      System.out.println("xs3_http_status : " + http_conn.getResponseCode());
      System.out.println("xs3_http_headers: " + http_conn.getHeaderFields());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != xs3_outstream) xs3_outstream.close();
      if (null != xs3_instream) xs3_instream.close();
    }
  }
 /**
  * save bitmap to file
  *
  * @param map
  * @param file
  * @throws IOException
  */
 public static void saveBitmap2File(Bitmap map, String file) throws IOException {
   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), 16 * 1024);
   map.compress(Bitmap.CompressFormat.PNG, DEFAULT_COMPRESS_QUALITY, bos);
   bos.flush();
   bos.close();
   bos = null;
 }
Beispiel #18
0
 /**
  * Using temp files (one per inner JAR/DLL) solves many issues: 1. There are no ways to load JAR
  * defined in a JarEntry directly into the JarFile object (see also #6 below). 2. Cannot use
  * memory-mapped files because they are using nio channels, which are not supported by JarFile
  * ctor. 3. JarFile object keeps opened JAR files handlers for fast access. 4. Deep resource in a
  * jar-in-jar does not have well defined URL. Making temp file with JAR solves this problem. 5.
  * Similar issues with native libraries: <code>ClassLoader.findLibrary()</code> accepts ONLY
  * string with absolute path to the file with native library. 6. Option
  * "java.protocol.handler.pkgs" does not allow access to nested JARs(?).
  *
  * @param inf JAR entry information.
  * @return temporary file object presenting JAR entry.
  * @throws JarClassLoaderException
  */
 private File createTempFile(JarEntryInfo inf) throws JarClassLoaderException {
   // Temp files directory:
   //   WinXP: C:/Documents and Settings/username/Local Settings/Temp/JarClassLoader
   //    Unix: /var/tmp/JarClassLoader
   if (dirTemp == null) {
     File dir = new File(System.getProperty("java.io.tmpdir"), TMP_SUB_DIRECTORY);
     if (!dir.exists()) {
       dir.mkdir();
     }
     chmod777(dir); // Unix - allow temp directory RW access to all users.
     if (!dir.exists() || !dir.isDirectory()) {
       throw new JarClassLoaderException("Cannot create temp directory " + dir.getAbsolutePath());
     }
     dirTemp = dir;
   }
   File fileTmp = null;
   try {
     fileTmp = File.createTempFile(inf.getName() + ".", null, dirTemp);
     fileTmp.deleteOnExit();
     chmod777(fileTmp); // Unix - allow temp file deletion by any user
     byte[] a_by = inf.getJarBytes();
     BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(fileTmp));
     os.write(a_by);
     os.close();
     return fileTmp;
   } catch (IOException e) {
     throw new JarClassLoaderException(
         String.format("Cannot create temp file '%s' for %s", fileTmp, inf.jarEntry), e);
   }
 } // createTempFile()
  public void testExport() throws Exception {
    String[] headers = {"数据", "字符", "日期", "日历", "是否", "null"};
    String[] properties = {"INT", "CHAR", "DATE", "CALENDAR", "BOOL", "NULL"};

    DolphinObject obj;
    List data = new ArrayList(10);
    for (int i = 1; i < 10; i++) {
      obj = new DolphinObject();
      data.add(obj);

      obj.setProperty(properties[0], i);
      obj.setProperty(properties[1], "你好" + i);
      obj.setProperty(properties[2], new Date());
      obj.setProperty(properties[3], new GregorianCalendar());
      obj.setProperty(properties[4], true);
      obj.setProperty(properties[5], null);
    }

    IConvertor converter = (IConvertor) PureFactory.getBean("SimpleConvertor");
    DolphinExportGoods goods = new DolphinExportGoods();
    goods.setName("你好");
    goods.setHeaders(headers);
    goods.setData(data, properties, converter);

    BufferedOutputStream bos = null;
    try {
      IExporter exporter = new ExcelExporterImpl();
      bos = new BufferedOutputStream(new FileOutputStream("export.xls"));
      exporter.export(bos, goods);
      System.out.println("Excel file created: " + new File("export.xls").getAbsolutePath());
    } finally {
      goods.clear();
      if (bos != null) bos.close();
    }
  }
  private boolean writeFile(byte[] data) {
    String directoryName = Environment.getExternalStorageDirectory().getPath() + DOWNLOAD_DIRECTORY;
    File f = new File(directoryName);

    if (!f.isDirectory()) {
      if (!f.mkdir()) {
        return false;
      }
    }

    String filename = directoryName + "/" + objects.getCName();
    File object = new File(filename);
    BufferedOutputStream bos = null;

    try {
      FileOutputStream fos = new FileOutputStream(object);
      bos = new BufferedOutputStream(fos);
      bos.write(data);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (bos != null) {
        try {
          bos.flush();
          bos.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
    return true;
  }
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public @ResponseBody String handleFileUpload(
      @RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

    System.out.println(name + " " + file.getOriginalFilename());
    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream =
            new BufferedOutputStream(
                new FileOutputStream(
                    new File(
                        path
                            + name
                            + "."
                            + FilenameUtils.getExtension(file.getOriginalFilename()))));

        stream.write(bytes);
        stream.close();
        return "You successfully uploaded " + name + "!";
      } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    } else {
      return "You failed to upload " + name + " because the file was empty.";
    }
  }
Beispiel #22
0
  /**
   * Unzip given file into given folder.
   *
   * @param fileZip : zip file to unzip.
   * @param dirOut : folder where to put the unzipped files.
   */
  public static void unzip(File fileZip, File dirOut) {
    try {
      byte[] buf = new byte[10 * 1024];
      if (!fileZip.canRead()) throw new IllegalArgumentException(fileZip.getAbsolutePath());
      if (!dirOut.isDirectory()) dirOut.mkdirs();
      if (!dirOut.isDirectory()) throw new IllegalArgumentException(dirOut.getAbsolutePath());

      FileInputStream fin = new FileInputStream(fileZip);
      ZipInputStream zin = new ZipInputStream(fin);
      ZipEntry ze = null;
      while ((ze = zin.getNextEntry()) != null) {
        File fileZe = new File(dirOut, ze.getName());
        Log.i("Zip", fileZe.getAbsolutePath());
        if (ze.isDirectory()) continue;
        assureParentExists(fileZe);
        BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(fileZe));
        while (true) {
          int read = zin.read(buf);
          if (-1 == read) break; // End of file.
          fout.write(buf, 0, read);
        }
        zin.closeEntry();
        fout.close();
      }
      zin.close();
    } catch (Exception e) {
      Log.e("MyZip", "unzip", e);
    }
  }
 public boolean createJar(File jarFilename, File... filesToAdd) {
   try {
     FileOutputStream stream = new FileOutputStream(jarFilename);
     JarOutputStream out = new JarOutputStream(stream, new Manifest());
     BufferedOutputStream bos = new BufferedOutputStream(out);
     for (File fileToAdd : filesToAdd) {
       if (fileToAdd == null || !fileToAdd.exists() || fileToAdd.isDirectory()) {
         continue; // Just in case...
       }
       JarEntry jarAdd = new JarEntry(fileToAdd.getName());
       jarAdd.setTime(fileToAdd.lastModified());
       out.putNextEntry(jarAdd);
       FileInputStream in = new FileInputStream(fileToAdd);
       BufferedInputStream bis = new BufferedInputStream(in);
       int data;
       while ((data = bis.read()) != -1) {
         bos.write(data);
       }
       bis.close();
       in.close();
     }
     bos.close();
     out.close();
     stream.close();
   } catch (FileNotFoundException e) {
     // skip not found file
   } catch (IOException e) {
     e.printStackTrace();
   }
   return true;
 }
 public static void measureReadingFile(File file, PrintWriter out) {
   try {
     long start = System.nanoTime();
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     BufferedOutputStream outToNull = new BufferedOutputStream(byteArrayOutputStream);
     BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
     long start1 = System.nanoTime();
     byte[] bytes = new byte[1024];
     int counter = 0;
     long start2 = System.nanoTime();
     while ((counter += in.read(bytes)) > 0) {
       outToNull.write(bytes, 0, counter);
     }
     in.close();
     outToNull.close();
     long stop = System.nanoTime(); // stop
     synchronized (out) {
       out.println(
           (double) (stop - start) / 1000000.
               + ", "
               + (double) (start1 - start) / 1000000.
               + ", "
               + (double) (start2 - start1) / 1000000.
               + ", "
               + (double) (stop - start2) / 1000000.); // + " " +
       threadCount++;
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Beispiel #25
0
  /** Upload multiple file using Spring Controller */
  @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
  public @ResponseBody String uploadMultipleFileHandler(
      @RequestParam("name") String[] names, @RequestParam("file") MultipartFile[] files) {

    if (files.length != names.length) return "Mandatory information missing";

    String message = "";
    for (int i = 0; i < files.length; i++) {
      MultipartFile file = files[i];
      String name = names[i];
      try {
        byte[] bytes = file.getBytes();

        // Creating the directory to store file
        String rootPath = System.getProperty("catalina.home");
        File dir = new File(rootPath + File.separator + "tmpFiles");
        if (!dir.exists()) dir.mkdirs();

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

        logger.info("Server File Location=" + serverFile.getAbsolutePath());

        message = message + "You successfully uploaded file=" + name + "<br />";
      } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
      }
    }
    return message;
  }
 public static void measureReadingHbase(HTable table, byte[] key, PrintWriter out) {
   try {
     long start1 = System.nanoTime();
     Get g = new Get(key);
     Result r = table.get(g);
     long start2 = System.nanoTime();
     byte[] value = r.getValue(Import.family, Import.qualifier);
     if (value != null) {
       long start3 = System.nanoTime();
       BufferedOutputStream outToNull = new BufferedOutputStream(new ByteArrayOutputStream());
       outToNull.write(value);
       outToNull.close();
       long stop = System.nanoTime(); // stop
       synchronized (out) {
         out.println(
             "NAN, "
                 + (double) (stop - start1) / 1000000.
                 + ", "
                 + (double) (start2 - start1) / 1000000.
                 + ", "
                 + (double) (start3 - start2) / 1000000.
                 + ", "
                 + (double) (stop - start3) / 1000000.); // +
         // " "
         // +
         threadCount++;
       }
     } else {
       System.out.println("No image is extracted with name key " + new String(key));
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 public void kopi(String sumber, String sasaran) throws IOException {
   FileInputStream masukan = null;
   FileOutputStream keluaran = null;
   BufferedInputStream masukanBuffer = null;
   BufferedOutputStream keluaranBuffer = null;
   try {
     masukan = new FileInputStream(sumber);
     masukanBuffer = new BufferedInputStream(masukan);
     keluaran = new FileOutputStream(sasaran);
     keluaranBuffer = new BufferedOutputStream(keluaran);
     int karakter = masukanBuffer.read();
     while (karakter != -1) {
       keluaranBuffer.write(karakter);
       karakter = masukanBuffer.read();
     }
     keluaranBuffer.flush();
   } finally {
     if (masukan != null) masukan.close();
     if (masukanBuffer != null) masukanBuffer.close();
     if (keluaran != null) keluaran.close();
     if (keluaranBuffer != null) {
       keluaranBuffer.close();
     }
   }
 }
  public static void main(String[] args) throws IOException {
    int bytesRead;
    int current = 0;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    Socket sock = null;
    try {
      sock = new Socket(SERVER, SOCKET_PORT);
      System.out.println("Connecting...");

      // receive file
      byte[] mybytearray = new byte[FILE_SIZE];
      InputStream is = sock.getInputStream();
      fos = new FileOutputStream(FILE_TO_RECEIVED);
      bos = new BufferedOutputStream(fos);
      bytesRead = is.read(mybytearray, 0, mybytearray.length);
      current = bytesRead;

      do {
        bytesRead = is.read(mybytearray, current, (mybytearray.length - current));
        if (bytesRead >= 0) current += bytesRead;
      } while (bytesRead > -1);

      bos.write(mybytearray, 0, current);
      bos.flush();
      System.out.println("File " + FILE_TO_RECEIVED + " downloaded (" + current + " bytes read)");
    } finally {
      if (fos != null) fos.close();
      if (bos != null) bos.close();
      if (sock != null) sock.close();
    }
  }
 /**
  * 获取网络上的文件
  *
  * @param URLName 地址
  * @throws Exception
  */
 public static byte[] getURLFile(String urlFile) throws Exception {
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int HttpResult = 0; // 服务器返回的状态
   URL url = new URL(urlFile); // 创建URL
   URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码urlconn.connect();
   HttpURLConnection httpconn = (HttpURLConnection) urlconn;
   HttpResult = httpconn.getResponseCode();
   if (HttpResult != HttpURLConnection.HTTP_OK) { // 不等于HTTP_OK说明连接不成功
     System.out.print("连接失败!");
   } else {
     BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());
     BufferedOutputStream bos = new BufferedOutputStream(os);
     byte[] buffer = new byte[1024]; // 创建存放输入流的缓冲
     int num = -1; // 读入的字节数
     while (true) {
       num = bis.read(buffer); // 读入到缓冲区
       if (num == -1) {
         bos.flush();
         break; // 已经读完
       }
       bos.flush();
       bos.write(buffer, 0, num);
     }
     bos.close();
     bis.close();
   }
   return os.toByteArray();
 }
 private void writeToFile(String file, byte[] data) throws IOException {
   File f = new File(file);
   BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
   out.write(data);
   out.flush();
   out.close();
 }