public void setTemplate(TemplateType type, InputStream inputStream) throws CoreException {
   File template = getTemplate(type);
   if (template != null) {
     if (!template.exists()) {
       try {
         File file = new File(template.getParent());
         file.mkdirs();
         template.createNewFile();
         FileOutputStream fos = new FileOutputStream(template);
         FileUtil.copy(inputStream, fos);
         fos.close();
       } catch (Exception e) {
         BonitaStudioLog.error(e);
       }
     } else {
       try {
         template.delete();
         template.createNewFile();
         FileOutputStream fos = new FileOutputStream(template);
         FileUtil.copy(inputStream, fos);
         fos.close();
       } catch (Exception e) {
         BonitaStudioLog.error(e);
       }
     }
   } else {
     throw new CoreException(Status.CANCEL_STATUS);
   }
 }
  private static void testSysOut(String fs, String exp, Object... args) {
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
      PrintStream saveOut = System.out;
      fos = new FileOutputStream("testSysOut");
      System.setOut(new PrintStream(fos));
      System.out.format(Locale.US, fs, args);
      fos.close();

      fis = new FileInputStream("testSysOut");
      byte[] ba = new byte[exp.length()];
      int len = fis.read(ba);
      String got = new String(ba);
      if (len != ba.length) fail(fs, exp, got);
      ck(fs, exp, got);

      System.setOut(saveOut);
    } catch (FileNotFoundException ex) {
      fail(fs, ex.getClass());
    } catch (IOException ex) {
      fail(fs, ex.getClass());
    } finally {
      try {
        if (fos != null) fos.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        fail(fs, ex.getClass());
      }
    }
  }
  public void deployFromAssets(File dest) throws IOException {
    Context ctx = softContext.get();
    if (ctx != null) {
      ArrayList<String> paths = new ArrayList<String>();
      AssetManager am = ctx.getAssets();
      walkAssets(am, "", paths);

      // TODO clean old dir
      wipeDirectoryTree(dest);

      // copy from assets to dest dir
      BufferedInputStream bis = null;
      FileOutputStream fos = null;
      byte[] buf = new byte[8096];
      try {
        int len = paths.size();
        for (int i = 0; i < len; i++) {
          String path = paths.get(i);
          File f = new File(path);
          if (f.getName().indexOf(".") > -1) {
            bis = new BufferedInputStream(am.open(path), 8096);
            File df = new File(dest, path);
            Log.d(TAG, "Copying to: " + df.getAbsolutePath(), Log.DEBUG_MODE);
            fos = new FileOutputStream(df);

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

            bis.close();
            bis = null;
            fos.close();
            fos = null;
          } else {
            File d = new File(dest, path);
            Log.d(TAG, "Creating directory: " + d.getAbsolutePath());
            d.mkdirs();
          }
        }
      } finally {
        if (bis != null) {
          try {
            bis.close();
          } catch (IOException e) {
            // Ignore
          }
          bis = null;
        }
        if (fos != null) {
          try {
            fos.close();
          } catch (IOException e) {
            // Ignore
          }
          fos = null;
        }
      }
    }
  }
 private void copy(String source, String dest) {
   FileInputStream in = null;
   FileOutputStream out = null;
   try {
     in = new FileInputStream(source);
     out = new FileOutputStream(dest);
     int len = -1;
     byte[] buffer = new byte[8096];
     while ((len = in.read(buffer)) != -1) {
       out.write(buffer, 0, len);
     }
     in.close();
     out.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (in != null) in.close();
     } catch (IOException e) {
     }
     try {
       if (out != null) out.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
示例#5
0
  /**
   * 将Base64的图片转化为jpg格式保存
   *
   * @param base64Data Base64图片数据
   * @param savePath 保存的路径
   * @return 返回图片的Bitmap
   */
  public static Bitmap base64ToBitmap(String base64Data, String savePath) {
    byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

    File file = new File(savePath);
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    try {
      boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
      if (isSuccess) {
        fos.flush();
        fos.close();
        return bitmap;
      } else {
        fos.close();
        return null;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
 /*
  * (non-Javadoc)
  *
  * @see
  * org.talend.designer.codegen.ISQLPatternSynchronizer#syncSQLPattern(org.talend.core.model.properties.SQLPatternItem
  * , boolean)
  */
 @Override
 public void syncSQLPattern(SQLPatternItem routineItem, boolean copyToTemp)
     throws SystemException {
   FileOutputStream fos = null;
   try {
     IFile file = getSQLPatternFile(routineItem);
     if (file == null) {
       return;
     }
     if (copyToTemp) {
       String routineContent = new String(routineItem.getContent().getInnerContent());
       File f = file.getLocation().toFile();
       fos = new FileOutputStream(f);
       fos.write(routineContent.getBytes());
       fos.close();
     }
     file.refreshLocal(1, null);
   } catch (CoreException e) {
     throw new SystemException(e);
   } catch (IOException e) {
     throw new SystemException(e);
   } finally {
     try {
       fos.close();
     } catch (Exception e) {
       // ignore me even if i'm null
     }
   }
 }
示例#7
0
 @BeforeClass
 public static void setUp() throws Exception {
   KEY = MessageDigest.getInstance("SHA-256").digest(ALIAS.getBytes());
   // Create a JKECS store containing a test secret key
   KeyStore store = KeyStore.getInstance("JCEKS");
   store.load(null, PASSWORD.toCharArray());
   store.setEntry(
       ALIAS,
       new KeyStore.SecretKeyEntry(new SecretKeySpec(KEY, "AES")),
       new KeyStore.PasswordProtection(PASSWORD.toCharArray()));
   // Create the test directory
   String dataDir = TEST_UTIL.getDataTestDir().toString();
   new File(dataDir).mkdirs();
   // Write the keystore file
   storeFile = new File(dataDir, "keystore.jks");
   FileOutputStream os = new FileOutputStream(storeFile);
   try {
     store.store(os, PASSWORD.toCharArray());
   } finally {
     os.close();
   }
   // Write the password file
   Properties p = new Properties();
   p.setProperty(ALIAS, PASSWORD);
   passwordFile = new File(dataDir, "keystore.pw");
   os = new FileOutputStream(passwordFile);
   try {
     p.store(os, "");
   } finally {
     os.close();
   }
 }
    @Override
    public void log(JSONObject logData, String fileName) throws SecurityException, IOException {
      File file = new File(activity.getFilesDir(), FILE_NAME0);
      File file2 = new File(activity.getFilesDir(), ANALYTICS_FILE_NAME0);

      try {
        if (!file.exists()
            || file.length() == 0 && !logData.getString("level").equals("ANALYTICS")) {
          // make a non-empty file so send() continues, but it will actually pick up data from this
          // mock
          FileOutputStream fos = new FileOutputStream(file);
          fos.write('a');
          fos.close();
        }
        if (!file2.exists()
            || file2.length() == 0 && logData.getString("level").equals("ANALYTICS")) {
          // make a non-empty file so sendAnalytics() continues, but it will actually pick up data
          // from this mock
          FileOutputStream fos = new FileOutputStream(file2);
          fos.write('a');
          fos.close();
        }
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      jsonObjects.put(logData);
    }
示例#9
0
  private void download(final String url, File file) throws IOException {
    URL u = new URL(url);
    HttpURLConnection huc = (HttpURLConnection) u.openConnection();
    huc.setRequestMethod("GET");
    huc.setReadTimeout(0);

    final long start = System.currentTimeMillis();
    long end;
    InputStream is = huc.getInputStream();

    int c;
    byte[] ba = new byte[LINE.length() + 6];
    FileOutputStream fos = new FileOutputStream(file);
    try {
      while ((c = is.read(ba)) != -1) {
        fos.write(ba, 0, c);
        fos.flush();
        Thread.sleep(100);
      }
      is.close();
      fos.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      end = System.currentTimeMillis();
      fos.flush();
      fos.close();
    }

    Assert.assertTrue("Should take more than 30 seconds", end - start >= 30000);
  }
示例#10
0
  public static void endSession() {
    if (sKeyLocationFile == null) {
      return;
    }
    try {
      sKeyLocationFile.close();
      // Write to log file
      // Write timestamp, settings,
      String out =
          DateFormat.format("MM:dd hh:mm:ss", Calendar.getInstance().getTime()).toString()
              + " BS: "
              + sBackspaceCount
              + " auto: "
              + sAutoSuggestCount
              + " manual: "
              + sManualSuggestCount
              + " typed: "
              + sWordNotInDictionaryCount
              + " undone: "
              + sAutoSuggestUndoneCount
              + " saved: "
              + ((float) (sActualChars - sTypedChars) / sActualChars)
              + "\n";
      sUserActionFile.write(out.getBytes());
      sUserActionFile.close();
      sKeyLocationFile = null;
      sUserActionFile = null;
    } catch (IOException ioe) {

    }
  }
示例#11
0
 // 边读边写
 private boolean readAndSaveAndConvert(
     InputStream inputStream, DataOutputStream dataOutputStream) {
   try {
     System.out.println("开始命名新文件:");
     String filename = "d:\\Website\\htdocs\\querydata\\audio\\" + System.currentTimeMillis();
     fileOutputStream = getFileOutputStream(filename + ".spx");
     fileOutputStreamBaidu = getFileOutputStream(filename + "_baidu.spx");
     System.out.println("新文件命名为:" + filename + ".spx");
     System.out.println("开始接收文件:");
     boolean finish = readAndWrite(inputStream, fileOutputStream, fileOutputStreamBaidu);
     fileOutputStream.close();
     fileOutputStreamBaidu.close();
     System.out.println("文件已接收并保存!");
     if (finish) {
       // 百度语音识别
       new Thread(new BaiduRecognizeDelete(filename + "_baidu", size)).start();
       // 科大讯飞识别
       new Thread(new ConvertRecognizeDelete(filename)).start();
     } else {
       socket.close();
       return false;
     }
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return true;
 }
示例#12
0
  /** @return success */
  private static final boolean genKeysCLI(String publicKeyFile, String privateKeyFile) {
    FileOutputStream fileOutputStream = null;

    I2PAppContext context = I2PAppContext.getGlobalContext();
    try {
      Object signingKeypair[] = context.keyGenerator().generateSigningKeypair();
      SigningPublicKey signingPublicKey = (SigningPublicKey) signingKeypair[0];
      SigningPrivateKey signingPrivateKey = (SigningPrivateKey) signingKeypair[1];

      fileOutputStream = new FileOutputStream(publicKeyFile);
      signingPublicKey.writeBytes(fileOutputStream);
      fileOutputStream.close();
      fileOutputStream = null;

      fileOutputStream = new FileOutputStream(privateKeyFile);
      signingPrivateKey.writeBytes(fileOutputStream);

      System.out.println("\r\nPrivate key written to: " + privateKeyFile);
      System.out.println("Public key written to: " + publicKeyFile);
      System.out.println("\r\nPublic key: " + signingPublicKey.toBase64() + "\r\n");
    } catch (Exception e) {
      System.err.println("Error writing keys:");
      e.printStackTrace();
      return false;
    } finally {
      if (fileOutputStream != null)
        try {
          fileOutputStream.close();
        } catch (IOException ioe) {
        }
    }
    return true;
  }
示例#13
0
 private void print() throws Exception {
   File dir = new File(DESTINATION_DIR);
   dir.mkdirs();
   // for (String className : mClassMap.keySet()) {
   for (Iterator it = mClassMap.keySet().iterator(); it.hasNext(); ) {
     String className = (String) it.next();
     // special handling for strange group tag.
     if (className == null) continue;
     HashMap /* <String, String> */ classMap = (HashMap) mClassMap.get(className);
     // System.out.println("\nClass:" + keys);
     FileOutputStream fs = new FileOutputStream(DESTINATION_DIR + "/" + className + ".java");
     // for (String orderString : mKeyOrder) {
     for (Iterator it2 = mKeyOrder.iterator(); it2.hasNext(); ) {
       String orderString = (String) it2.next();
       if (classMap.containsKey(orderString)) {
         String string = (String) classMap.get(orderString);
         fs.write(string.getBytes());
         // System.out.print(string);
       }
     }
     fs.close();
   }
   // write binding to disk
   if (true) {
     FileOutputStream fs = new FileOutputStream(DESTINATION_DIR + "/binding.xml");
     fs.write(mBindingXml.toString().getBytes());
     fs.close();
   }
 }
示例#14
0
 /**
  * read from input stream,write into output stream
  *
  * @param fileInStream
  * @param fileOutStream
  */
 public static void write(SvnFileInputStream fileInStream, FileOutputStream fileOutStream)
     throws Exception {
   if (null != fileInStream && null != fileOutStream) {
     try {
       byte[] tmp = new byte[BUFFER_SIZE];
       int k = 0;
       while ((k = fileInStream.read(tmp)) > -1) {
         fileOutStream.write(tmp, 0, k);
       }
       fileOutStream.flush();
       fileOutStream.close();
       fileOutStream = null;
       fileInStream.close();
       fileInStream = null;
     } catch (Exception e) {
       if (null != fileInStream) {
         fileInStream.close();
         fileInStream = null;
       }
       if (null != fileOutStream) {
         fileOutStream.flush();
         fileOutStream.close();
         fileOutStream = null;
       }
       throw new Exception("error in write into output stream.");
     }
   }
 }
示例#15
0
 /**
  * read from input stream,write into output stream
  *
  * @param fileInStream InputStream
  * @param fileOutStream SvnFileOutputStream
  */
 public static void streamCopy(InputStream fileInStream, FileOutputStream fileOutStream)
     throws Exception {
   if (null != fileInStream && null != fileOutStream) {
     try {
       byte[] tmpBuf = new byte[BUFFER_SIZE];
       int tmpLen = 0;
       while ((tmpLen = fileInStream.read(tmpBuf)) > 0) {
         fileOutStream.write(tmpBuf, 0, tmpLen);
       }
       fileOutStream.flush();
       fileOutStream.close();
       fileOutStream = null;
       fileInStream.close();
       fileInStream = null;
     } catch (Exception e) {
       if (null != fileInStream) {
         fileInStream.close();
         fileInStream = null;
       }
       if (null != fileOutStream) {
         fileOutStream.flush();
         fileOutStream.close();
         fileOutStream = null;
       }
       throw new Exception("error in write into output stream.");
     }
   }
 }
示例#16
0
    @Override
    public void write(String file) throws IOException {
      if (cos != null) {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(cos.toByteArray());
        fos.close();
      } else {
        File targetFile = new File(file);
        if (targetFile.exists()) targetFile.delete();
        if (partFile.renameTo(targetFile) == false) {
          FileInputStream in = null;
          FileOutputStream out = null;
          try {
            Utils.copyStream(
                in = new FileInputStream(partFile), out = new FileOutputStream(targetFile), 0);
          } catch (IOException ioe) {
            throw new IOException("Can't move or move file " + partFile + " to " + file);
          } finally {
            if (in != null)
              try {
                in.close();
              } catch (IOException e) {

              }
            if (out != null)
              try {
                out.close();
              } catch (IOException e) {

              }
          }
        } else partFile = targetFile;
      }
    }
示例#17
0
  public static void setupLocalSolver(String codeBase, String host, int port) {
    if (sInstance == null || sLocalSolverInitialized) return;
    synchronized (sInstance) {
      try {
        File webInfDir = new File(ApplicationProperties.getBasePath());
        File timetablingDir = webInfDir.getParentFile();
        File solverDir = new File(timetablingDir, "solver");
        File solverJnlp = new File(solverDir, "solver.jnlp");

        Document document = (new SAXReader()).read(solverJnlp);
        Element root = document.getRootElement();
        root.attribute("codebase")
            .setValue(codeBase + (codeBase.endsWith("/") ? "" : "/") + "solver");

        boolean hostSet = false, portSet = false;
        Element resources = root.element("resources");
        for (Iterator i = resources.elementIterator("property"); i.hasNext(); ) {
          Element property = (Element) i.next();
          if ("tmtbl.solver.register.host".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(host);
            hostSet = true;
          }
          if ("tmtbl.solver.register.port".equals(property.attributeValue("name"))) {
            property.attribute("value").setValue(String.valueOf(port));
            portSet = true;
          }
        }

        if (!hostSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.host")
              .addAttribute("value", host);
        }
        if (!portSet) {
          resources
              .addElement("property")
              .addAttribute("name", "tmtbl.solver.register.port")
              .addAttribute("value", String.valueOf(port));
        }

        FileOutputStream fos = null;
        try {
          fos = new FileOutputStream(solverJnlp);
          (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(document);
          fos.flush();
          fos.close();
          fos = null;
        } finally {
          try {
            if (fos != null) fos.close();
          } catch (IOException e) {
          }
        }
      } catch (Exception e) {
        sLog.debug("Unable to alter solver.jnlp, reason: " + e.getMessage(), e);
      }
      sLocalSolverInitialized = true;
    }
  }
  @Test
  public void testKeygenToFileOutputStream()
      throws NoSuchAlgorithmException, NoSuchProviderException, IOException {
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(1024, random);

    KeyPair pair = keyGen.generateKeyPair();

    final PrivateKey priv = pair.getPrivate();
    final PublicKey pub = pair.getPublic();

    // Write the private key to a file
    FileOutputStream privOS = new FileOutputStream("RSAPrivateKey.key");
    Assert.assertNotNull(privOS);
    privOS.write(priv.getEncoded());
    privOS.close();

    // Write the private key to a file
    FileOutputStream publicOS = new FileOutputStream("RSAPublicKey.key");
    Assert.assertNotNull(publicOS);
    publicOS.write(pub.getEncoded());
    publicOS.close();
  }
示例#19
0
  public static void updatePropertiesFile(
      File propsFile, Map<String, String> values, String comment) throws IOException {
    Properties props = new Properties();
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      fis = new FileInputStream(propsFile);
      props.load(fis);
      fis.close();
      fis = null;
      props.putAll(values);

      fos = new FileOutputStream(propsFile);
      props.store(fos, comment);
      fos.close();
      fos = null;

    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (Exception ex) {

        }
      }
      if (fos != null) {
        try {
          fos.close();
        } catch (Exception ex) {
        }
      }
    }
  }
示例#20
0
  private String buildCartFile(String newFileName, String path, byte cartHeader[]) {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      fis = new FileInputStream(path);
      File f = new File(newFileName);
      f.createNewFile();
      fos = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      fos.write(cartHeader);

      int bytesRead = 0;
      while ((bytesRead = fis.read(buffer)) > 0) {
        fos.write(buffer, 0, bytesRead);
      }
      fis.close();
      fos.close();
      return newFileName;
    } catch (Throwable e) {
      e.printStackTrace();
      try {
        if (null != fis) fis.close();
        if (null != fos) fos.close();
      } catch (Throwable ee) {
        ee.printStackTrace();
      }
      return null;
    }
  }
示例#21
0
  public void saveToFile() {
    Log.i(LOG_TAG, "Saving to file...");
    try {
      FileOutputStream fos = openFileOutput("cs_pinger_icmp", Context.MODE_PRIVATE);
      ObjectOutputStream os = new ObjectOutputStream(fos);
      os.writeObject(icmpPingSettings);
      os.close();
      fos.close();

      fos = openFileOutput("cs_pinger_http", Context.MODE_PRIVATE);
      os = new ObjectOutputStream(fos);
      os.writeObject(httpPingSettings);
      os.close();
      fos.close();

      fos = openFileOutput("cs_pinger_https", Context.MODE_PRIVATE);
      os = new ObjectOutputStream(fos);
      os.writeObject(httpsPingSettings);
      os.close();
      fos.close();
    } catch (Exception e) {
      StringWriter errors = new StringWriter();
      e.printStackTrace(new PrintWriter(errors));
      Log.e(LOG_TAG, "File write error!\n" + errors.toString());
    }
  }
示例#22
0
    @Override
    public void export(
        MolgenisRequest request,
        String fileName,
        TupleTable tupleTable,
        int totalPages,
        int currentPage)
        throws TableException, IOException {
      try {
        final File tempDir = new File(System.getProperty("java.io.tmpdir"));
        final File spssFile = File.createTempFile("spssExport", ".sps", tempDir);
        final File spssCsvFile = File.createTempFile("csvSpssExport", ".csv", tempDir);
        // TODO: instruction .txt file.
        final File zipExport = File.createTempFile("spssExport", ".zip", tempDir);

        final FileOutputStream spssFileStream = new FileOutputStream(spssFile);
        final FileOutputStream spssCsvFileStream = new FileOutputStream(spssCsvFile);
        final SPSSExporter spssExporter = new SPSSExporter(tupleTable);
        spssExporter.export(spssCsvFileStream, spssFileStream, spssCsvFile.getName());

        spssCsvFileStream.close();
        spssFileStream.close();
        ZipUtils.compress(
            Arrays.asList(spssFile, spssCsvFile), zipExport, DirectoryStructure.EXCLUDE_DIR);
        HeaderHelper.setHeader(
            request.getResponse(), "application/octet-stream", fileName + ".zip");
        exportFile(zipExport, request.getResponse());
      } catch (Exception e) {
        throw new TableException(e);
      }
    }
示例#23
0
  private static void saveOpts(JSONObject obj) {
    String fileDir = System.getProperty("user.dir");
    File file = new File(fileDir, DATA_FILE);
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(file);
      Properties pro = new Properties();
      Iterator it = obj.keys();
      while (it.hasNext()) {
        String key = (String) it.next();
        String value = obj.getString(key);
        pro.setProperty(key, value);
      }
      pro.store(fos, " ");
      fos.close();
    } catch (Exception e) {

    } finally {
      try {
        if (null != fos) fos.close();
      } catch (IOException e) {

      }
    }
  }
示例#24
0
  public static void main(String[] args) {
    try {
      BufferedImage img = ImageIO.read(new File(args[0]));

      BufferedImage intImg =
          new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = intImg.createGraphics();
      g2.drawImage(img, null, null);

      Encoder enc = new Encoder();

      //			long startTime = System.nanoTime();
      ByteBuffer frame = enc.encodeFrame(intImg, true);
      //			long endTime = System.nanoTime();

      //			long time = (endTime - startTime) / 1000000;
      //			System.out.print(String.format("Encode time %d ms\n", time));

      FileOutputStream out = new FileOutputStream(args[1] + "Key.vp8");
      out.getChannel().write(frame);
      out.close();

      frame = enc.encodeFrame(intImg, false);

      out = new FileOutputStream(args[1] + "Inter.vp8");
      out.getChannel().write(frame);
      out.close();

      System.out.println("Success!");

    } catch (IOException ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
  }
示例#25
0
  public boolean setFileBinaryBase64(String fileName, String base64) throws APIException {
    FileOutputStream stream = null;
    try {
      File f = new File(fileName);

      f.createNewFile();

      stream = new FileOutputStream(f);
      stream.write(Base64.decode(base64));
      try {
        stream.close();
      } catch (IOException e) {
        throw new APIException(fileName + " could not be closed!");
      }
    } catch (Exception e) {
      throw new APIException(fileName + " could not have its files extracte!");
    } finally {
      try {
        stream.flush();
        stream.close();
      } catch (Exception e) {
        throw new APIException(fileName + " could not be closed!");
      }
    }
    return true;
  }
示例#26
0
 public void writeToFile(File certFile, File keyFile)
     throws IOException, CertificateEncodingException {
   FileOutputStream keyOutputStream = null;
   FileOutputStream certOutputStream = null;
   try {
     keyOutputStream = new FileOutputStream(keyFile);
     certOutputStream = new FileOutputStream(certFile);
     saveKey(keyOutputStream);
     saveCertificateChain(certOutputStream);
   } finally {
     try {
       if (keyOutputStream != null) {
         keyOutputStream.close();
       }
     } catch (IOException e) {
       logger.warn("Could not close stream on save of key to file. " + keyFile.getPath());
     }
     try {
       if (certOutputStream != null) {
         certOutputStream.close();
       }
     } catch (IOException e) {
       logger.warn(
           "Could not close stream on save certificate chain to file. " + certFile.getPath());
     }
   }
 }
  // 生成tar并压缩成tar.gz
  public static void WriteToTarGzip(String folderPath, String targzipFilePath) {
    byte[] buf = new byte[1024]; // 设定读入缓冲区尺寸
    try {
      // 建立压缩文件输出流
      FileOutputStream fout = new FileOutputStream(targzipFilePath);
      // 建立tar压缩输出流
      TarOutputStream tout = new TarOutputStream(fout);
      addFiles(tout, folderPath);
      tout.close();
      fout.close();

      // 建立压缩文件输出流
      FileOutputStream gzFile = new FileOutputStream(targzipFilePath + ".gz");
      // 建立gzip压缩输出流
      GZIPOutputStream gzout = new GZIPOutputStream(gzFile);
      // 打开需压缩文件作为文件输入流
      FileInputStream tarin = new FileInputStream(targzipFilePath); // targzipFilePath是文件全路径
      int len;
      while ((len = tarin.read(buf)) != -1) {
        gzout.write(buf, 0, len);
      }
      gzout.close();
      gzFile.close();
      tarin.close();

    } catch (FileNotFoundException e) {
      System.out.println(e);
    } catch (IOException e) {
      System.out.println(e);
    }

    File tarfile = new File(targzipFilePath);
    tarfile.delete();
  }
示例#28
0
  // System-dependent portion of ProcessBuilder.start()
  static Process start(
      String cmdarray[],
      java.util.Map<String, String> environment,
      String dir,
      ProcessBuilder.Redirect[] redirects,
      boolean redirectErrorStream)
      throws IOException {
    String envblock = ProcessEnvironment.toEnvironmentBlock(environment);

    FileInputStream f0 = null;
    FileOutputStream f1 = null;
    FileOutputStream f2 = null;

    try {
      long[] stdHandles;
      if (redirects == null) {
        stdHandles = new long[] {-1L, -1L, -1L};
      } else {
        stdHandles = new long[3];

        if (redirects[0] == Redirect.PIPE) stdHandles[0] = -1L;
        else if (redirects[0] == Redirect.INHERIT)
          stdHandles[0] = fdAccess.getHandle(FileDescriptor.in);
        else {
          f0 = new FileInputStream(redirects[0].file());
          stdHandles[0] = fdAccess.getHandle(f0.getFD());
        }

        if (redirects[1] == Redirect.PIPE) stdHandles[1] = -1L;
        else if (redirects[1] == Redirect.INHERIT)
          stdHandles[1] = fdAccess.getHandle(FileDescriptor.out);
        else {
          f1 = newFileOutputStream(redirects[1].file(), redirects[1].append());
          stdHandles[1] = fdAccess.getHandle(f1.getFD());
        }

        if (redirects[2] == Redirect.PIPE) stdHandles[2] = -1L;
        else if (redirects[2] == Redirect.INHERIT)
          stdHandles[2] = fdAccess.getHandle(FileDescriptor.err);
        else {
          f2 = newFileOutputStream(redirects[2].file(), redirects[2].append());
          stdHandles[2] = fdAccess.getHandle(f2.getFD());
        }
      }

      return new ProcessImpl(cmdarray, envblock, dir, stdHandles, redirectErrorStream);
    } finally {
      // In theory, close() can throw IOException
      // (although it is rather unlikely to happen here)
      try {
        if (f0 != null) f0.close();
      } finally {
        try {
          if (f1 != null) f1.close();
        } finally {
          if (f2 != null) f2.close();
        }
      }
    }
  }
示例#29
0
 @Override
 public void saveSync() {
   if (mData == null) {
     Log.w(TAG, "[saveSync]why mData==null???", new Throwable());
     return;
   }
   FileOutputStream out = null;
   try {
     // Write to a temporary file and rename it to the final name.
     // This
     // avoids other apps reading incomplete data.
     out = new FileOutputStream(mTempFilePath);
     out.write(mData);
     out.close();
   } catch (IOException e) {
     Log.e(TAG, "[saveSync]Failed to write image", e);
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
         Log.e(TAG, "[saveSync]exception : ", e);
       }
     }
   }
 }
示例#30
0
 public static boolean saveFile(String path, byte[] file) {
   path = Constants.WIN_FILE_DIRECTORY + path;
   FileOutputStream fos = null;
   boolean result = false;
   try {
     File someFile = new File(path);
     fos = new FileOutputStream(someFile);
     fos.write(file);
     fos.flush();
     fos.close();
     result = true;
   } catch (FileNotFoundException ex) {
     Logger.getLogger(MyFileUtils.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IOException ex) {
     Logger.getLogger(MyFileUtils.class.getName()).log(Level.SEVERE, null, ex);
   } finally {
     try {
       fos.close();
     } catch (IOException ex) {
       Logger.getLogger(MyFileUtils.class.getName()).log(Level.SEVERE, null, ex);
     } finally {
       return result;
     }
   }
 }