コード例 #1
1
ファイル: StreamPump.java プロジェクト: philjord/tools
  @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
      }
    }
  }
コード例 #2
1
  /**
   * @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();
  }
コード例 #3
0
ファイル: 000061.java プロジェクト: stepthom/tcp.lda
  /**
   * 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();
  }
コード例 #4
0
 /**
  * 获取网络上的文件
  *
  * @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();
 }
コード例 #5
0
  public LineManager(String filename) throws IOException {
    mNumLines = 0;

    BufferedReader content = new BufferedReader(new FileReader(filename), BLOCK_SIZE);

    // For Directory
    BufferedOutputStream directory = new BufferedOutputStream(new FileOutputStream(DIRECTORY_PATH));
    int pageNo = 0; // 0-based index to make computation easier
    int slotNo = 1;

    // For Data
    ByteBuffer dataBuffer = ByteBuffer.allocate(BLOCK_SIZE);
    BufferedOutputStream data = new BufferedOutputStream(new FileOutputStream(DATA_PATH));
    int initialIndex = BLOCK_SIZE - 3 * INT_SIZE; // Each slot index is
    // offset, length pair
    // Each page ends with
    // # slots on page
    int indexPos = initialIndex;
    String curLine;
    // KNOWN BUG: lineLen > BLOCK_SIZE
    while ((curLine = content.readLine()) != null) {
      int lineLen = curLine.length();
      byte[] lineBytes = curLine.getBytes("US-ASCII");
      if (dataBuffer.position() + lineLen > indexPos) { // End of page
        dataBuffer.putInt(BLOCK_SIZE - INT_SIZE, slotNo - 1);
        // Write number of slots on page
        data.write(dataBuffer.array());

        // Reset info
        dataBuffer.clear();
        indexPos = initialIndex;
        pageNo++;
        slotNo = 1;
      }
      dataBuffer.putInt(indexPos, dataBuffer.position());
      dataBuffer.putInt(indexPos + INT_SIZE, lineLen);
      dataBuffer.put(lineBytes);
      indexPos -= 2 * INT_SIZE;

      directory.write(LineManager.intToBytes(pageNo));
      directory.write(LineManager.intToBytes(slotNo));

      slotNo++;
      mNumLines++;
    }
    data.write(dataBuffer.array());
    data.flush();
    directory.flush();
    content.close();
    data.close();
    directory.close();

    mDirectoryFile = new RandomAccessFile(DIRECTORY_PATH, "r");
    mDataFile = new RandomAccessFile(DATA_PATH, "r");
  }
コード例 #6
0
ファイル: Helper.java プロジェクト: nainoi/Confly
  public static void createThumbnail(String filePath, String folderName) {
    FileInputStream epubInputStream = null;
    BufferedOutputStream bos = null;
    try {
      epubInputStream = new FileInputStream(new File(filePath));
      String lastPath = filePath.substring(filePath.lastIndexOf('/') + 1);
      String savePath = getThumbnailDirectory(folderName) + "/" + lastPath;

      if (!Helper.fileExits(savePath)) {
        byte[] cis = FileEncrypt.decrypt_data(epubInputStream);
        if (cis == null) return;

        FileOutputStream outputStream = new FileOutputStream(new File(savePath));
        bos = new BufferedOutputStream(outputStream);
        bos.write(cis, 0, cis.length);
        bos.flush();
        bos.close();

        byte[] imageData = null;

        // PDFView pdfView = new PDFView(getApplicationContext(),null);

        Bitmap imageBitmap = decodeFile(new File(savePath));

        int targetWidth = 150;

        double aspectRatio = (double) imageBitmap.getHeight() / (double) imageBitmap.getWidth();
        int targetHeight = (int) (targetWidth * aspectRatio);

        // imageBitmap = Bitmap.createScaledBitmap(imageBitmap,(int)(imageBitmap.getWidth()*0.4),
        // (int)(imageBitmap.getHeight()*0.4), true);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, targetWidth, targetHeight, true);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
        imageData = baos.toByteArray();

        outputStream = new FileOutputStream(new File(savePath));
        bos = new BufferedOutputStream(outputStream);
        bos.write(imageData, 0, imageData.length);
        bos.flush();
        bos.close();

        Thread.sleep(10);
      }
      // InputStream is = new ByteArrayInputStream(cis);
      // imageView.setImageBitmap(decodeFile(new File(savePath)));
    } catch (OutOfMemoryError e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
      // imageView.setImageResource(R.drawable.no_image_detail);
    }
  }
コード例 #7
0
  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();
    }
  }
コード例 #8
0
ファイル: FileUtil.java プロジェクト: weizhidb/gitTestOne
  // 复制文件
  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();
    }
  }
コード例 #9
0
ファイル: EntradaController.java プロジェクト: Emmy02/mateo
 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();
     }
   }
 }
コード例 #10
0
 private void saveImage(byte[] data) {
   try {
     BitmapFactory.Options opts = new BitmapFactory.Options();
     opts.inJustDecodeBounds = true;
     BitmapFactory.decodeByteArray(data, 0, data.length, opts);
     DisplayMetrics dm = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(dm);
     opts.inSampleSize = calculateInSampleSize(opts, dm.heightPixels, dm.widthPixels);
     opts.inPurgeable = true;
     opts.inInputShareable = true;
     opts.inTempStorage = new byte[64 * 1024];
     opts.inJustDecodeBounds = false;
     Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
     if (bm != null) {
       bm = Util.rotate(bm, getRotate());
       File file = new File(filePath);
       BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
       bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
       bos.flush();
       bos.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #11
0
ファイル: ModEDMUpdater.java プロジェクト: RoboRave/EDM
  private void downloadFile(String link) throws MalformedURLException, IOException {
    URL url = new URL(link);
    URLConnection conn = url.openConnection();
    InputStream is = conn.getInputStream();

    // this is just a little information showing the download size of the file
    int max = conn.getContentLength();
    console.setText(console.getText() + "\ndownload file... \nupdatesize: " + max + " bytes");

    // this will output the download to the mods folder
    BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(new File(ModsLoc)));
    byte[] buffer = new byte[32 * 1024];
    int bytesRead = 0;
    int in = 0;

    while ((bytesRead = is.read(buffer)) != -1) {
      in += bytesRead;
      fout.write(buffer, 0, bytesRead);
    }

    fout.flush();
    fout.close();
    is.close();

    // after its finished we will print to our console
    console.setText(console.getText() + "\ndownload complete");
  }
コード例 #12
0
 /**
  * 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;
 }
コード例 #13
0
  private int extractZipEntry(String out_path, ZipInputStream zip, int total_size, String mes) {
    BufferedOutputStream out = null;
    try {
      out = new BufferedOutputStream(new FileOutputStream(out_path));
    } catch (Exception e) {
      sendMessage(-2, 0, "Failed to create file: " + e.toString());
      return -1;
    }
    ;

    int total_read = 0;
    try {
      int len = zip.read(buf);
      while (len >= 0) {
        if (len > 0) out.write(buf, 0, len);
        total_read += len;
        sendMessage(total_read, total_size, mes);
        len = zip.read(buf);
        try {
          Thread.sleep(1);
        } catch (InterruptedException e) {
        }
      }
      out.flush();
      out.close();
    } catch (java.io.IOException e) {
      sendMessage(-2, 0, "Failed to write: " + e.toString());
      return -1;
    }

    return 0;
  }
コード例 #14
0
ファイル: OsmbLzma.java プロジェクト: OpenSeaMap/chart-base
  /**
   * This encodes a file or directory in 7z/lzma.
   *
   * @param strInFileName
   * @param strOutFileName
   * @throws IOException
   */
  public static void encode7z(String strInFileName, String strOutFileName) throws IOException {
    java.nio.file.Path inPath = FileSystems.getDefault().getPath(strInFileName);
    java.io.File inFile = new java.io.File(strInFileName);
    java.io.File outFile = new java.io.File(strOutFileName);

    java.io.BufferedInputStream inStream =
        new java.io.BufferedInputStream(new java.io.FileInputStream(inFile));
    java.io.BufferedOutputStream outStream =
        new java.io.BufferedOutputStream(new java.io.FileOutputStream(outFile));

    boolean eos = false;
    {
      SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();
      encoder.SetEndMarkerMode(eos);
      encoder.WriteCoderProperties(outStream);
      long fileSize;
      if (eos) fileSize = -1;
      else fileSize = inFile.length();
      for (int i = 0; i < 8; i++) outStream.write((int) (fileSize >>> (8 * i)) & 0xFF);
      encoder.Code(inStream, outStream, -1, -1, null);
    }
    outStream.flush();
    outStream.close();
    inStream.close();
  }
コード例 #15
0
ファイル: FileUploadHandler.java プロジェクト: nicolas360/my
  @Override
  public void messageReceived(IoSession session, Object message) {
    System.out.println("server received");

    try {
      if (message instanceof FileUploadRequest) {
        // FileUploadRequest 为传递过程中使用的DO。
        FileUploadRequest request = (FileUploadRequest) message;
        System.out.println(request.getFilename());
        if (out == null) {
          // 新建一个文件输入对象BufferedOutputStream,随便定义新文件的位置
          out = new BufferedOutputStream(new FileOutputStream("D:/log/" + request.getFilename()));
          out.write(request.getFileContent());
        } else {
          out.write(request.getFileContent());
        }
        count += request.getFileContent().length;

      } else if (message instanceof String) {
        if (((String) message).equals("finish")) {
          System.out.println("size is" + count);
          // 这里是进行文件传输后,要进行flush和close否则传递的文件不完整。
          out.flush();
          out.close();
          // 回执客户端信息,上传文件成功
          session.write("success");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #16
0
ファイル: FileUtil.java プロジェクト: simonharrer/jabref
  /**
   * Copies a file.
   *
   * @param source File Source file
   * @param dest File Destination file
   * @param deleteIfExists boolean Determines whether the copy goes on even if the file exists.
   * @return boolean Whether the copy succeeded, or was stopped due to the file already existing.
   * @throws IOException
   */
  public static boolean copyFile(File source, File dest, boolean deleteIfExists)
      throws IOException {

    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    try {
      // Check if the file already exists.
      if (dest.exists()) {
        if (!deleteIfExists) {
          return false;
          // else dest.delete();
        }
      }

      in = new BufferedInputStream(new FileInputStream(source));
      out = new BufferedOutputStream(new FileOutputStream(dest));
      int el;
      // int tell = 0;
      while ((el = in.read()) >= 0) {
        out.write(el);
      }
    } finally {
      if (out != null) {
        out.flush();
        out.close();
      }
      if (in != null) {
        in.close();
      }
    }
    return true;
  }
コード例 #17
0
ファイル: AVCClipCatTest.java プロジェクト: s4ke/jcodec
  @Test
  public void testAVCClipCat() throws IOException {
    File f1 = new File("src/test/resources/AVCClipCatTest/seq_1.mp4");
    File f2 = new File("src/test/resources/AVCClipCatTest/seq_2.mp4");
    File f3 = new File("src/test/resources/AVCClipCatTest/seq_3.mp4");

    MovieBox m1 = MP4Util.parseMovie(f1);
    MovieBox m2 = MP4Util.parseMovie(f2);
    MovieBox m3 = MP4Util.parseMovie(f3);

    VirtualTrack t1 =
        new AVCClipTrack(new RealTrack(m1, m1.getVideoTrack(), new FilePool(f1, 10)), 60, 120);
    VirtualTrack t2 =
        new AVCClipTrack(new RealTrack(m2, m2.getVideoTrack(), new FilePool(f2, 10)), 60, 120);
    VirtualTrack t3 =
        new AVCClipTrack(new RealTrack(m3, m3.getVideoTrack(), new FilePool(f3, 10)), 60, 120);

    AVCConcatTrack ct = new AVCConcatTrack(t1, t2, t3);
    VirtualMovie vm = new VirtualMP4Movie(ct);

    MovieRange range = new MovieRange(vm, 0, vm.size());

    BufferedOutputStream out =
        new BufferedOutputStream(
            new FileOutputStream(
                new File(System.getProperty("user.home"), "Desktop/cat_avc_clip.mp4")));
    IOUtils.copy(range, out);
    out.flush();
    out.close();
  }
コード例 #18
0
ファイル: Service.java プロジェクト: CSUMYH/NetSocketExam
  public static void main(String[] args) {
    try {
      socketserv = new ServerSocket(12348);
      while (true) {
        Socket socket = socketserv.accept();
        JOptionPane.showMessageDialog(null, "Á¬½Óµ½12348");
        System.out.println(123);
        File file = new File("../Exam1/target.pdf");
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        byte[] bt = new byte[1024];
        int len = 0;
        while ((len = bis.read(bt)) != -1) {
          bos.write(bt, 0, len);
          // System.out.println(bt.toString());	    bos.flush();

        }
        bos.flush();
        bis.close();
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #19
0
  public String registConnection(String registMessage) {
    try {
      InetAddress address = InetAddress.getByName(this.host);
      Socket clientSocket = new Socket(address, this.port);

      if (clientSocket == null) return ":C101";

      BufferedInputStream clientIn = new BufferedInputStream(clientSocket.getInputStream());
      BufferedOutputStream clientOut = new BufferedOutputStream(clientSocket.getOutputStream());

      if (clientOut == null) return ":C101";
      if (clientIn == null) return ":C101";
      byte[] buffer = new byte[2048];
      buffer = registMessage.getBytes();

      clientOut.write(buffer);
      clientOut.flush();

      buffer = new byte[1024];
      clientIn.read(buffer, 0, buffer.length);

      String message = new String(buffer).trim();
      clientOut.close();
      clientIn.close();
      clientSocket.close();

      return message;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ":R301";
  }
コード例 #20
0
ファイル: StorageManager.java プロジェクト: sincisco/microon
  public static State saveFileByInputStream(InputStream is, String path) {
    State state = null;

    File tmpFile = getTmpFile();

    byte[] dataBuf = new byte[2048];
    BufferedInputStream bis = new BufferedInputStream(is, 8192);
    try {
      BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile), 8192);

      int count = 0;
      while ((count = bis.read(dataBuf)) != -1) {
        bos.write(dataBuf, 0, count);
      }
      bos.flush();
      bos.close();

      state = saveTmpFile(tmpFile, path);

      if (!state.isSuccess()) {
        tmpFile.delete();
      }

      return state;
    } catch (IOException localIOException) {
      log.error(localIOException);
    }
    return new BaseState(false, 4);
  }
コード例 #21
0
  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;
  }
コード例 #22
0
  /**
   * Handle a Magnet request via a socket (for TCP handling). Deiconify the application, fire MAGNET
   * request and return true as a sign that LimeWire is running.
   */
  public void fireControlThread(Socket socket, boolean magnet) {
    LOG.trace("enter fireControl");

    Thread.currentThread().setName("IncomingControlThread");
    try {
      // Only allow control from localhost
      if (!NetworkUtils.isLocalHost(socket)) {
        if (LOG.isWarnEnabled())
          LOG.warn("Invalid control request from: " + socket.getInetAddress().getHostAddress());
        return;
      }

      // First read extra parameter
      socket.setSoTimeout(Constants.TIMEOUT);
      ByteReader br = new ByteReader(socket.getInputStream());
      // read the first line. if null, throw an exception
      String line = br.readLine();
      socket.setSoTimeout(0);

      BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
      String s = CommonUtils.getUserName() + "\r\n";
      // system internal, so use system encoding
      byte[] bytes = s.getBytes();
      out.write(bytes);
      out.flush();
      if (magnet) handleMagnetRequest(line);
      else handleTorrentRequest(line);
    } catch (IOException e) {
      LOG.warn("Exception while responding to control request", e);
    } finally {
      IOUtils.close(socket);
    }
  }
コード例 #23
0
  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();
    }
  }
コード例 #24
0
  public static String store(InputStream in, String basePath, long userId, String imgName)
      throws IOException {
    String filePath =
        MessageFormat.format(
            Config.getString(Config.KEY_STORAGE_PATH_FORMAT),
            basePath,
            userId,
            DateUtils.date2Str(
                new Date(),
                Config.getString(
                    Config.KEY_STORAGE_DATE_FORMAT, DateUtils.DEFAULT_DATE_SIMPLE_FORMAT)),
            imgName);

    File file = new File(filePath);
    file.getParentFile().mkdirs();
    BufferedOutputStream bufOut = new BufferedOutputStream(new FileOutputStream(file));
    byte[] block = new byte[BUF_SIZE];
    int n = -1;
    while ((n = in.read(block)) != -1) {
      bufOut.write(block, 0, n);
    }
    bufOut.flush();
    bufOut.close();
    in.close();
    return filePath;
  }
コード例 #25
0
ファイル: FileUtils.java プロジェクト: Darlyyuhui/hand
  /**
   * 拷贝文件
   *
   * @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;
  }
コード例 #26
0
  public void run() {

    byte[] tmp = new byte[10000];
    int read;
    try {
      FileInputStream fis = new FileInputStream(fileToSend.getFile());

      read = fis.read(tmp);
      while (read != -1) {
        baos.write(tmp, 0, read);
        read = fis.read(tmp);
        System.out.println(read);
      }
      fis.close();
      baos.writeTo(sWriter);
      sWriter.flush();
      baos.flush();
      baos.close();
      System.out.println("fileSent");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {

      this.closeSocket();
    }
  }
コード例 #27
0
 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();
     }
   }
 }
コード例 #28
0
 public void flush() throws IOException {
   if (out instanceof BufferedOutputStream) {
     ((BufferedOutputStream) out).flush();
   } else {
     out.flush();
   }
 }
コード例 #29
0
 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();
 }
コード例 #30
0
    public void copyTo(File destination) throws IOException {
      BufferedInputStream bIS = null;
      BufferedOutputStream bOS = null;

      try {
        bIS = new BufferedInputStream(new FileInputStream(this));
        bOS = new BufferedOutputStream(new FileOutputStream(destination));
        byte[] buffer = new byte[2048];
        int bytesRead;
        while ((bytesRead = bIS.read(buffer, 0, buffer.length)) != -1) {
          bOS.write(buffer, 0, bytesRead);
        }
        bOS.flush();
      } finally {
        if (bIS != null) {
          try {
            bIS.close();
            bIS = null;
          } catch (IOException e) {
          }
        }
        if (bOS != null) {
          try {
            bOS.close();
            bOS = null;
          } catch (IOException e) {
          }
        }
      }
    }