Java Code Examples for java.io.BufferedOutputStream

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project addis, under directory /application/src/main/java/org/drugis/addis/entities/.

Source file: DomainManager.java

  32 
vote

private void saveAddisData(AddisData data,OutputStream os) throws IOException {
  try {
    BufferedOutputStream buf=new BufferedOutputStream(os);
    FilterOutputStream fos=new XMLStreamFilter(buf);
    JAXBHandler.marshallAddisData(data,fos);
    buf.flush();
    fos.close();
  }
 catch (  JAXBException e) {
    throw new RuntimeException(e);
  }
}
 

Example 2

From project ajah, under directory /ajah-util/src/main/java/com/ajah/util/io/file/.

Source file: FileUtils.java

  32 
vote

/** 
 * Writes a string to a file.
 * @param file The file to write to.
 * @param string The string to write.
 * @return The number of bytes written.
 * @throws IOException If the file could not be written to.
 */
public static int write(final File file,final String string) throws IOException {
  BufferedOutputStream out=null;
  try {
    file.getParentFile().mkdirs();
    out=new BufferedOutputStream(new FileOutputStream(file));
    out.write(string.getBytes(UTF8));
    log.fine("Wrote " + string.length() + " bytes");
    return string.length();
  }
  finally {
    IOUtils.safeClose(out);
  }
}
 

Example 3

From project ambrose, under directory /common/src/main/java/azkaban/common/utils/.

Source file: Props.java

  32 
vote

/** 
 * Store only those properties defined at this local level
 * @param file The file to write to
 * @throws IOException If the file can't be found or there is an io error
 */
public void storeLocal(File file) throws IOException {
  BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(file));
  try {
    storeLocal(out);
  }
  finally {
    out.close();
  }
}
 

Example 4

From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/hash/.

Source file: PersistentHash.java

  32 
vote

private synchronized void appendEntryToStore(Message message) throws IOException {
  String filename=message.getKey();
  File file=new File(dirname,filename);
  FileOutputStream fos=new FileOutputStream(file,true);
  BufferedOutputStream bos=new BufferedOutputStream(fos);
  ObjectOutputStream oos=new ObjectOutputStream(bos);
  oos.writeObject(message);
  oos.flush();
  oos.close();
  fos.flush();
  fos.close();
}
 

Example 5

From project azkaban, under directory /azkaban-common/src/java/azkaban/common/utils/.

Source file: Props.java

  32 
vote

/** 
 * Store only those properties defined at this local level
 * @param file The file to write to
 * @throws IOException If the file can't be found or there is an io error
 */
public void storeLocal(File file) throws IOException {
  BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(file));
  try {
    storeLocal(out);
  }
  finally {
    out.close();
  }
}
 

Example 6

From project big-data-plugin, under directory /shims/api/src/org/pentaho/hbase/shim/api/.

Source file: HBaseValueMeta.java

  32 
vote

/** 
 * Encodes and object via serialization
 * @param obj the object to encode
 * @return an array of bytes containing the serialized object
 * @throws IOException if serialization fails
 */
public static byte[] encodeObject(Object obj) throws IOException {
  ByteArrayOutputStream bos=new ByteArrayOutputStream();
  BufferedOutputStream buf=new BufferedOutputStream(bos);
  ObjectOutputStream oos=new ObjectOutputStream(buf);
  oos.writeObject(obj);
  buf.flush();
  return bos.toByteArray();
}
 

Example 7

From project Carolina-Digital-Repository, under directory /djatoka-cdr/src/gov/lanl/adore/djatoka/io/writer/.

Source file: BMPWriter.java

  32 
vote

/** 
 * Write a BufferedImage instance using implementation to the  provided OutputStream.
 * @param bi a BufferedImage instance to be serialized
 * @param os OutputStream to output the image to
 * @throws FormatIOException
 */
public void write(BufferedImage bi,OutputStream os) throws FormatIOException {
  if (bi != null) {
    BufferedOutputStream bos=null;
    try {
      bos=new BufferedOutputStream(os);
      ImageEncoder enc=ImageCodec.createImageEncoder("BMP",bos,param);
      enc.encode(bi);
    }
 catch (    IOException e) {
      logger.error(e,e);
    }
  }
}
 

Example 8

From project commons-io, under directory /src/main/java/org/apache/commons/io/.

Source file: FileUtils.java

  32 
vote

/** 
 * Writes the <code>toString()</code> value of each item in a collection to the specified <code>File</code> line by line. The specified character encoding and the line ending will be used.
 * @param file  the file to write to
 * @param encoding  the encoding to use, {@code null} means platform default
 * @param lines  the lines to write, {@code null} entries produce blank lines
 * @param lineEnding  the line separator to use, {@code null} is system default
 * @param append if {@code true}, then the lines will be added to the end of the file rather than overwriting
 * @throws IOException in case of an I/O error
 * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
 * @since 2.1
 */
public static void writeLines(File file,String encoding,Collection<?> lines,String lineEnding,boolean append) throws IOException {
  FileOutputStream out=null;
  try {
    out=openOutputStream(file,append);
    final BufferedOutputStream buffer=new BufferedOutputStream(out);
    IOUtils.writeLines(lines,lineEnding,buffer,encoding);
    buffer.flush();
    out.close();
  }
  finally {
    IOUtils.closeQuietly(out);
  }
}
 

Example 9

From project core_1, under directory /runtime/src/main/java/org/switchyard/internal/io/graph/.

Source file: InputStreamGraph.java

  32 
vote

/** 
 * {@inheritDoc}
 */
@Override public void compose(InputStream object,Map<Integer,Object> visited) throws IOException {
  int bs=Serializer.DEFAULT_BUFFER_SIZE;
  BufferedInputStream bis=new BufferedInputStream(object,bs);
  ByteArrayOutputStream baos=new ByteArrayOutputStream(bs);
  BufferedOutputStream bos=new BufferedOutputStream(baos,bs);
  byte[] buff=new byte[bs];
  int read=0;
  while ((read=bis.read(buff)) != -1) {
    bos.write(buff,0,read);
  }
  bos.flush();
  setBytes(baos.toByteArray());
}
 

Example 10

From project datafu, under directory /src/java/datafu/linkanalysis/.

Source file: PageRank.java

  32 
vote

private void writeEdgesToDisk() throws IOException {
  this.edgesFile=File.createTempFile("fastgraph",null);
  FileOutputStream outStream=new FileOutputStream(this.edgesFile);
  BufferedOutputStream bufferedStream=new BufferedOutputStream(outStream);
  this.edgeDataOutputStream=new DataOutputStream(bufferedStream);
  for (  int edgeData : edges) {
    this.edgeDataOutputStream.writeInt(edgeData);
  }
  this.edges.clear();
  usingEdgeDiskCache=true;
}
 

Example 11

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/io/.

Source file: PropUtils.java

  32 
vote

public final static Properties storeProperties(final Properties props,final File file) throws IOException {
  if (!file.getParentFile().exists())   file.getParentFile().mkdirs();
  if (!file.exists())   file.createNewFile();
  BufferedOutputStream out=null;
  try {
    final FileOutputStream os=new FileOutputStream(file);
    out=new BufferedOutputStream(os);
    props.store(out,"DAWB Properties. Please do not edit this file.");
  }
  finally {
    IOUtils.close(out,"Storing properties for file " + IOUtils.fileInfo(file));
  }
  return props;
}
 

Example 12

From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model/src/main/java/com/isencia/passerelle/workbench/model/utils/.

Source file: PropUtils.java

  32 
vote

public final static Properties storeProperties(final Properties props,final File file) throws IOException {
  if (!file.getParentFile().exists())   file.getParentFile().mkdirs();
  if (!file.exists())   file.createNewFile();
  BufferedOutputStream out=null;
  try {
    final FileOutputStream os=new FileOutputStream(file);
    out=new BufferedOutputStream(os);
    props.store(out,"DAWB Properties. Please do not edit this file.");
  }
  finally {
    IOUtils.close(out,"Storing properties for file " + IOUtils.fileInfo(file));
  }
  return props;
}
 

Example 13

From project dcm4che, under directory /dcm4che-net/src/main/java/org/dcm4che/net/service/.

Source file: BasicCStoreSCP.java

  32 
vote

private void spool(Association as,Attributes fmi,PDVInputStream data,File file,MessageDigest digest) throws IOException {
  LOG.info("{}: M-WRITE {}",as,file);
  file.getParentFile().mkdirs();
  FileOutputStream fout=new FileOutputStream(file);
  BufferedOutputStream bout=new BufferedOutputStream(digest == null ? fout : new DigestOutputStream(fout,digest));
  DicomOutputStream out=new DicomOutputStream(bout,UID.ExplicitVRLittleEndian);
  out.writeFileMetaInformation(fmi);
  try {
    data.copyTo(out);
  }
  finally {
    out.close();
  }
}
 

Example 14

From project Diver, under directory /ca.uvic.chisel.diver.mylyn.logger/src/ca/uvic/chisel/diver/mylyn/logger/logging/.

Source file: SimpleLogger.java

  32 
vote

public SimpleLogger() throws FileNotFoundException {
  IPath state=MylynLogger.getDefault().getStateLocation();
  File file=new File(state.toFile(),"simpleLog.log");
  FileOutputStream fStream=new FileOutputStream(file,true);
  BufferedOutputStream bStream=new BufferedOutputStream(fStream);
  output=new PrintStream(bStream,true);
}
 

Example 15

From project dolphin, under directory /com.sysdeo.eclipse.tomcat/src/com/sysdeo/eclipse/tomcat/.

Source file: FileUtil.java

  32 
vote

/** 
 * Copie un fichier vers un autre
 */
public static void copyFile(File inputFile,File outputFile) throws IOException {
  BufferedInputStream fr=new BufferedInputStream(new FileInputStream(inputFile));
  BufferedOutputStream fw=new BufferedOutputStream(new FileOutputStream(outputFile));
  byte[] buf=new byte[8192];
  int n;
  while ((n=fr.read(buf)) >= 0)   fw.write(buf,0,n);
  fr.close();
  fw.close();
}
 

Example 16

From project droid-fu, under directory /src/main/java/com/github/droidfu/cachefu/.

Source file: HttpResponseCache.java

  32 
vote

@Override protected void writeValueToDisk(File file,ResponseData data) throws IOException {
  BufferedOutputStream ostream=new BufferedOutputStream(new FileOutputStream(file));
  ostream.write(data.getStatusCode());
  ostream.write(data.getResponseBody());
  ostream.close();
}
 

Example 17

From project droidkit, under directory /src/org/droidkit/util/tricks/.

Source file: IOTricks.java

  32 
vote

public static void saveObject(Object object,File fileName) throws IOException {
  File tempFileName=new File(fileName.toString() + "-tmp");
  FileOutputStream fileOut=new FileOutputStream(tempFileName);
  BufferedOutputStream buffdOut=new BufferedOutputStream(fileOut,32 * 1024);
  ObjectOutputStream objectOut=new ObjectOutputStream(buffdOut);
  objectOut.writeObject(object);
  objectOut.close();
  buffdOut.close();
  fileOut.close();
  fileName.delete();
  tempFileName.renameTo(fileName);
}
 

Example 18

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: FileUtils.java

  31 
vote

static void writejarEntry(JarInputStream jarfile,ZipEntry entry,String path,boolean verbose) throws IOException {
  File tofp=new File(path + File.separator + entry.getName());
  tofp.mkdirs();
  if (entry.isDirectory()) {
    return;
  }
 else {
    tofp.delete();
  }
  int buffer=(int)(entry.getSize() > 0 ? entry.getSize() : 1024);
  int count=0;
  int sumcount=0;
  byte data[]=new byte[buffer];
  FileOutputStream fos=null;
  try {
    fos=new FileOutputStream(tofp);
  }
 catch (  Exception e) {
    System.err.println("Unable to extract file:" + tofp + " from "+ path);
    return;
  }
  BufferedOutputStream dest=new BufferedOutputStream(fos,buffer);
  while ((count=jarfile.read(data,0,buffer)) != -1) {
    dest.write(data,0,count);
    sumcount+=count;
  }
  if (verbose)   System.out.println("Uncompressed: " + entry.getName() + " size: "+ sumcount+ " with buffersize: "+ buffer);
  dest.flush();
  dest.close();
}
 

Example 19

From project aether-core, under directory /aether-impl/src/main/java/org/eclipse/aether/internal/impl/.

Source file: DefaultFileProcessor.java

  31 
vote

public void write(File target,InputStream source) throws IOException {
  mkdirs(target.getAbsoluteFile().getParentFile());
  OutputStream fos=null;
  try {
    fos=new BufferedOutputStream(new FileOutputStream(target));
    copy(fos,source,null);
    fos.close();
  }
  finally {
    close(fos);
  }
}
 

Example 20

From project Airports, under directory /src/com/nadmm/airports/notams/.

Source file: NotamService.java

  31 
vote

private void fetchNotams(String icaoCode,File notamFile) throws IOException {
  InputStream in=null;
  String params=String.format(NOTAM_PARAM,icaoCode);
  HttpsURLConnection conn=(HttpsURLConnection)NOTAM_URL.openConnection();
  conn.setRequestProperty("Connection","close");
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.setUseCaches(false);
  conn.setConnectTimeout(30 * 1000);
  conn.setReadTimeout(30 * 1000);
  conn.setRequestMethod("POST");
  conn.setRequestProperty("User-Agent","Mozilla/5.0 (X11; U; Linux i686; en-US)");
  conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length",Integer.toString(params.length()));
  OutputStream faa=conn.getOutputStream();
  faa.write(params.getBytes("UTF-8"));
  faa.close();
  int response=conn.getResponseCode();
  if (response == HttpURLConnection.HTTP_OK) {
    in=conn.getInputStream();
    ArrayList<String> notams=parseNotamsFromHtml(in);
    in.close();
    BufferedOutputStream cache=new BufferedOutputStream(new FileOutputStream(notamFile));
    for (    String notam : notams) {
      cache.write(notam.getBytes());
      cache.write('\n');
    }
    cache.close();
  }
}
 

Example 21

From project Android-File-Manager, under directory /src/com/nexes/manager/.

Source file: ApplicationBackup.java

  31 
vote

public void run(){
  BufferedInputStream mBuffIn;
  BufferedOutputStream mBuffOut;
  Message msg;
  int len=mDataSource.size();
  int read=0;
  for (int i=0; i < len; i++) {
    ApplicationInfo info=mDataSource.get(i);
    String source_dir=info.sourceDir;
    String out_file=source_dir.substring(source_dir.lastIndexOf("/") + 1,source_dir.length());
    try {
      mBuffIn=new BufferedInputStream(new FileInputStream(source_dir));
      mBuffOut=new BufferedOutputStream(new FileOutputStream(BACKUP_LOC + out_file));
      while ((read=mBuffIn.read(mData,0,BUFFER)) != -1)       mBuffOut.write(mData,0,read);
      mBuffOut.flush();
      mBuffIn.close();
      mBuffOut.close();
      msg=new Message();
      msg.what=SET_PROGRESS;
      msg.obj=i + " out of " + len+ " apps backed up";
      mHandler.sendMessage(msg);
    }
 catch (    FileNotFoundException e) {
      e.printStackTrace();
    }
catch (    IOException e) {
      e.printStackTrace();
    }
  }
  mHandler.sendEmptyMessage(FINISH_PROGRESS);
}
 

Example 22

From project Android-File-Manager-Tablet, under directory /src/com/nexes/manager/tablet/.

Source file: FileManager.java

  31 
vote

/** 
 * @param old		the file to be copied
 * @param newDir	the directory to move the file to
 * @return
 */
public int copyToDirectory(String old,String newDir){
  File old_file=new File(old);
  File temp_dir=new File(newDir);
  byte[] data=new byte[BUFFER];
  int read=0;
  if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) {
    String file_name=old.substring(old.lastIndexOf("/"),old.length());
    File cp_file=new File(newDir + file_name);
    try {
      BufferedOutputStream o_stream=new BufferedOutputStream(new FileOutputStream(cp_file));
      BufferedInputStream i_stream=new BufferedInputStream(new FileInputStream(old_file));
      while ((read=i_stream.read(data,0,BUFFER)) != -1)       o_stream.write(data,0,read);
      o_stream.flush();
      i_stream.close();
      o_stream.close();
    }
 catch (    FileNotFoundException e) {
      Log.e("FileNotFoundException",e.getMessage());
      return -1;
    }
catch (    IOException e) {
      Log.e("IOException",e.getMessage());
      return -1;
    }
  }
 else   if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
    String files[]=old_file.list();
    String dir=newDir + old.substring(old.lastIndexOf("/"),old.length());
    int len=files.length;
    if (!new File(dir).mkdir())     return -1;
    for (int i=0; i < len; i++)     copyToDirectory(old + "/" + files[i],dir);
  }
 else   if (!temp_dir.canWrite())   return -1;
  return 0;
}
 

Example 23

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.

Source file: AndroidFlashcards.java

  31 
vote

private void ensureInstructions(){
  File f=new File(sdDir + File.separator + "flashcards/android_flashcards_instructions.xml");
  if (!f.exists()) {
    try {
      BufferedInputStream bis=new BufferedInputStream(getResources().openRawResource(R.raw.android_flashcards_instructions));
      BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(f));
      int i;
      while ((i=bis.read()) != -1)       bos.write(i);
      bos.close();
      bis.close();
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
}
 

Example 24

From project Android-GifStitch, under directory /src/com/phunkosis/gifstitch/encoder/.

Source file: GifEncoder.java

  31 
vote

/** 
 * Initiates writing of a GIF file with the specified name.
 * @param file String containing output file name.
 * @return false if open or initial write failed.
 */
public boolean start(String file){
  boolean ok=true;
  try {
    out=new BufferedOutputStream(new FileOutputStream(file));
    ok=start(out);
    closeStream=true;
  }
 catch (  IOException e) {
    ok=false;
  }
  return started=ok;
}
 

Example 25

From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.

Source file: OcrInitAsyncTask.java

  31 
vote

/** 
 * Unzips the given Gzipped file to the given destination, and deletes the gzipped file.
 * @param zippedFile The gzipped file to be uncompressed
 * @param outFilePath File to unzip to, including path
 * @throws FileNotFoundException
 * @throws IOException
 */
private void gunzip(File zippedFile,File outFilePath) throws FileNotFoundException, IOException {
  int uncompressedFileSize=getGzipSizeUncompressed(zippedFile);
  Integer percentComplete;
  int percentCompleteLast=0;
  int unzippedBytes=0;
  final Integer progressMin=0;
  int progressMax=100 - progressMin;
  publishProgress("Uncompressing data for " + languageName + "...",progressMin.toString());
  String extension=zippedFile.toString().substring(zippedFile.toString().length() - 16);
  if (extension.equals(".tar.gz.download")) {
    progressMax=50;
  }
  GZIPInputStream gzipInputStream=new GZIPInputStream(new BufferedInputStream(new FileInputStream(zippedFile)));
  OutputStream outputStream=new FileOutputStream(outFilePath);
  BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream);
  final int BUFFER=8192;
  byte[] data=new byte[BUFFER];
  int len;
  while ((len=gzipInputStream.read(data,0,BUFFER)) > 0) {
    bufferedOutputStream.write(data,0,len);
    unzippedBytes+=len;
    percentComplete=(int)((unzippedBytes / (float)uncompressedFileSize) * progressMax) + progressMin;
    if (percentComplete > percentCompleteLast) {
      publishProgress("Uncompressing data for " + languageName + "...",percentComplete.toString());
      percentCompleteLast=percentComplete;
    }
  }
  gzipInputStream.close();
  bufferedOutputStream.flush();
  bufferedOutputStream.close();
  if (zippedFile.exists()) {
    zippedFile.delete();
  }
}
 

Example 26

From project android-rackspacecloud, under directory /src/com/rackspacecloud/android/.

Source file: ContainerObjectDetails.java

  31 
vote

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) {
        e.printStackTrace();
      }
    }
  }
  return true;
}
 

Example 27

From project AndroidCommon, under directory /src/com/asksven/andoid/common/contrib/.

Source file: Util.java

  31 
vote

public static ArrayList<String> run(String shell,String[] commands){
  ArrayList<String> output=new ArrayList<String>();
  try {
    Process process=Runtime.getRuntime().exec(shell);
    BufferedOutputStream shellInput=new BufferedOutputStream(process.getOutputStream());
    BufferedReader shellOutput=new BufferedReader(new InputStreamReader(process.getInputStream()));
    for (    String command : commands) {
      Log.i(TAG,"command: " + command);
      shellInput.write((command + " 2>&1\n").getBytes());
    }
    shellInput.write("exit\n".getBytes());
    shellInput.flush();
    String line;
    while ((line=shellOutput.readLine()) != null) {
      output.add(line);
    }
    process.waitFor();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
catch (  InterruptedException e) {
    e.printStackTrace();
  }
  return output;
}
 

Example 28

From project android_packages_apps_Gallery, under directory /src/com/android/camera/.

Source file: ThumbnailController.java

  31 
vote

public boolean storeData(String filePath){
  if (mUri == null) {
    return false;
  }
  FileOutputStream f=null;
  BufferedOutputStream b=null;
  DataOutputStream d=null;
  try {
    f=new FileOutputStream(filePath);
    b=new BufferedOutputStream(f,BUFSIZE);
    d=new DataOutputStream(b);
    d.writeUTF(mUri.toString());
    mThumb.compress(Bitmap.CompressFormat.PNG,100,d);
    d.close();
  }
 catch (  IOException e) {
    return false;
  }
 finally {
    MenuHelper.closeSilently(f);
    MenuHelper.closeSilently(b);
    MenuHelper.closeSilently(d);
  }
  return true;
}
 

Example 29

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: DiskCache.java

  31 
vote

private void writeIndex(){
  File tempFile=null;
  final String tempFilePath=mCacheDirectoryPath;
  final String indexFilePath=getIndexFilePath();
  try {
    tempFile=File.createTempFile("DiskCache",null,new File(tempFilePath));
  }
 catch (  Exception e) {
    Log.e(TAG,"Unable to create or tempFile " + tempFilePath);
    return;
  }
  try {
    final FileOutputStream fileOutput=new FileOutputStream(tempFile);
    final BufferedOutputStream bufferedOutput=new BufferedOutputStream(fileOutput,1024);
    final DataOutputStream dataOutput=new DataOutputStream(bufferedOutput);
    final int numRecords=mIndexMap.size();
    dataOutput.writeInt(INDEX_HEADER_MAGIC);
    dataOutput.writeInt(INDEX_HEADER_VERSION);
    dataOutput.writeShort(mTailChunk);
    dataOutput.writeInt(numRecords);
    for (int i=0; i < numRecords; ++i) {
      final long key=mIndexMap.keyAt(i);
      final Record record=mIndexMap.valueAt(i);
      dataOutput.writeLong(key);
      dataOutput.writeShort(record.chunk);
      dataOutput.writeInt(record.offset);
      dataOutput.writeInt(record.size);
      dataOutput.writeInt(record.sizeOnDisk);
      dataOutput.writeLong(record.timestamp);
    }
    dataOutput.close();
    tempFile.renameTo(new File(indexFilePath));
  }
 catch (  Exception e) {
    Log.e(TAG,"Unable to write the index file " + indexFilePath);
    tempFile.delete();
  }
}
 

Example 30

From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/util/.

Source file: Util.java

  31 
vote

public static ArrayList<String> run(String shell,String[] commands){
  ArrayList<String> output=new ArrayList<String>();
  try {
    Process process=Runtime.getRuntime().exec(shell);
    BufferedOutputStream shellInput=new BufferedOutputStream(process.getOutputStream());
    BufferedReader shellOutput=new BufferedReader(new InputStreamReader(process.getInputStream()));
    for (    String command : commands) {
      Log.i(TAG,"command: " + command);
      shellInput.write((command + " 2>&1\n").getBytes());
    }
    shellInput.write("exit\n".getBytes());
    shellInput.flush();
    String line;
    while ((line=shellOutput.readLine()) != null) {
      Log.d(TAG,"command output: " + line);
      output.add(line);
    }
    process.waitFor();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
catch (  InterruptedException e) {
    e.printStackTrace();
  }
  return output;
}
 

Example 31

From project anode, under directory /app/src/org/meshpoint/anode/util/.

Source file: TarExtractor.java

  31 
vote

public void unpack(File src,File dest) throws IOException {
  File tarFile=new File(src.getAbsolutePath() + ".tar");
  byte[] buf=new byte[1024];
  GZIPInputStream zis=null;
  zis=new GZIPInputStream(new FileInputStream(src));
  FileOutputStream tarfos=new FileOutputStream(tarFile);
  int count;
  while ((count=zis.read(buf,0,1024)) != -1)   tarfos.write(buf,0,count);
  tarfos.close();
  zis.close();
  TarInputStream tis=new TarInputStream(new BufferedInputStream(new FileInputStream(tarFile)));
  TarEntry entry;
  while ((entry=tis.getNextEntry()) != null) {
    File entryFile=new File(dest,entry.getName());
    File parentDir=new File(entryFile.getParent());
    if (!parentDir.isDirectory() && !parentDir.mkdirs())     throw new IOException("TarExtractor.unpack(): unable to create directory");
    FileOutputStream fos=new FileOutputStream(entryFile);
    BufferedOutputStream bos=new BufferedOutputStream(fos);
    while ((count=tis.read(buf)) != -1)     bos.write(buf,0,count);
    bos.flush();
    bos.close();
  }
  tis.close();
  tarFile.delete();
}
 

Example 32

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: FileUtils.java

  31 
vote

/** 
 * Copies the content of the input stream within the given dest file. The dest file must not exist.
 * @param is
 * @param dest
 */
public static void cp(InputStream is,File dest){
  if (dest.exists()) {
    throw new IllegalArgumentException("Destination must not exist.");
  }
  BufferedInputStream bis=null;
  BufferedOutputStream bos=null;
  try {
    bis=new BufferedInputStream(is);
    FileOutputStream fos=new FileOutputStream(dest);
    bos=new BufferedOutputStream(fos);
    final byte[] buffer=new byte[1024 * 4];
    int read;
    while (true) {
      read=bis.read(buffer);
      if (read == -1) {
        break;
      }
      bos.write(buffer,0,read);
    }
  }
 catch (  Exception e) {
    throw new RuntimeException("Error while copying stream into file.",e);
  }
 finally {
    StreamUtils.closeGracefully(bis);
    StreamUtils.closeGracefully(bos);
  }
}
 

Example 33

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: JarTask.java

  31 
vote

private void writeManifest(JarOutputStream jarOut) throws IOException {
  ZipEntry e=new ZipEntry(JarFile.MANIFEST_NAME);
  jarOut.putNextEntry(e);
  manifest.write(new BufferedOutputStream(jarOut));
  jarOut.closeEntry();
}
 

Example 34

From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/filemanager/.

Source file: FileManager.java

  31 
vote

public static void downloadFile(String source,String target) throws IOException {
  BufferedInputStream in=new BufferedInputStream(new URL(source).openStream());
  java.io.FileOutputStream fos=new java.io.FileOutputStream(target);
  java.io.BufferedOutputStream bout=new BufferedOutputStream(fos,1024);
  byte data[]=new byte[1024];
  while (in.read(data,0,1024) >= 0) {
    bout.write(data);
  }
  bout.close();
  in.close();
}
 

Example 35

From project apps-for-android, under directory /Panoramio/src/com/google/android/panoramio/.

Source file: BitmapUtils.java

  31 
vote

/** 
 * Loads a bitmap from the specified url. This can take a while, so it should not be called from the UI thread.
 * @param url The location of the bitmap asset
 * @return The bitmap, or null if it could not be loaded
 */
public static Bitmap loadBitmap(String url){
  Bitmap bitmap=null;
  InputStream in=null;
  BufferedOutputStream out=null;
  try {
    in=new BufferedInputStream(new URL(url).openStream(),IO_BUFFER_SIZE);
    final ByteArrayOutputStream dataStream=new ByteArrayOutputStream();
    out=new BufferedOutputStream(dataStream,IO_BUFFER_SIZE);
    copy(in,out);
    out.flush();
    final byte[] data=dataStream.toByteArray();
    bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
  }
 catch (  IOException e) {
    Log.e(TAG,"Could not load Bitmap from: " + url);
  }
 finally {
    closeStream(in);
    closeStream(out);
  }
  return bitmap;
}
 

Example 36

From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/storage/.

Source file: PersistentDatastore.java

  31 
vote

private static long consume(Value value,File dst) throws IOException {
  BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(dst));
  try {
    InputStream in=value.getContent();
    try {
      long length=0;
      byte[] buffer=new byte[4 * 1024];
      int len=-1;
      while ((len=in.read(buffer)) != -1) {
        out.write(buffer,0,len);
        length+=len;
      }
      return length;
    }
  finally {
      IoUtils.close(in);
    }
  }
  finally {
    IoUtils.close(out);
  }
}
 

Example 37

From project arquillian-container-gae, under directory /gae-common/src/main/java/org/jboss/arquillian/container/common/.

Source file: FixedExplodedExporter.java

  31 
vote

protected void processNode(ArchivePath path,Node node){
  final String assetFilePath=path.get();
  final File assetFile=new File(outputDirectory,assetFilePath);
  final File assetParent=assetFile.getParentFile();
  if (!assetParent.exists()) {
    if (!assetParent.mkdirs()) {
      throw new IllegalArgumentException("Failed to write asset.  Unable to create parent directory.");
    }
  }
  try {
    final boolean isDirectory=(node.getAsset() == null);
    if (isDirectory) {
      if (!assetFile.exists()) {
        if (!assetFile.mkdirs()) {
          throw new IllegalArgumentException("Failed to write directory: " + assetFile.getAbsolutePath());
        }
      }
    }
 else {
      try {
        if (log.isLoggable(Level.FINE)) {
          log.fine("Writing asset " + path.get() + " to "+ assetFile.getAbsolutePath());
        }
        final InputStream assetInputStream=node.getAsset().openStream();
        final FileOutputStream assetFileOutputStream=new FileOutputStream(assetFile);
        final BufferedOutputStream assetBufferedOutputStream=new BufferedOutputStream(assetFileOutputStream,8192);
        copyWithClose(assetInputStream,assetBufferedOutputStream);
      }
 catch (      final Exception e) {
        throw new IllegalArgumentException("Failed to write asset " + path + " to "+ assetFile,e);
      }
    }
  }
 catch (  final RuntimeException e) {
    throw e;
  }
catch (  final Exception e) {
    throw new IllegalArgumentException("Unexpected error encountered in export of " + node,e);
  }
}
 

Example 38

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/parser/.

Source file: Parser.java

  31 
vote

public void parseStream(InputStream inputStream){
  try {
    File tmp=File.createTempFile(Parser.class.getName(),".tmp");
    BufferedInputStream in=new BufferedInputStream(inputStream);
    BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(tmp));
    byte[] buf=new byte[1024];
    int len;
    while ((len=inputStream.read(buf)) > 0) {
      out.write(buf,0,len);
    }
    out.close();
    in.close();
    parseFileTempFile(tmp);
  }
 catch (  IOException e) {
    throw new ParsingException(e);
  }
}
 

Example 39

From project arquillian-showcase, under directory /extensions/weld-servlet/src/main/java/org/jboss/arquillian/extension/cdi/.

Source file: WeldServletDeploymentAppender.java

  31 
vote

@Override public Archive<?> createAuxiliaryArchive(){
  File settingsXml=null;
  InputStream in=null;
  BufferedOutputStream out=null;
  try {
    settingsXml=File.createTempFile("arquillian-","-settings.xml");
    settingsXml.deleteOnExit();
    in=WeldServletDeploymentAppender.class.getResourceAsStream("jboss-repository-settings.xml");
    out=new BufferedOutputStream(new FileOutputStream(settingsXml));
    byte[] buffer=new byte[1024];
    int len;
    while ((len=in.read(buffer)) != -1) {
      out.write(buffer,0,len);
    }
  }
 catch (  IOException ioe) {
    throw new IllegalStateException("Could not read settings.xml from classpath");
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      IOException ioe) {
      }
    }
    if (out != null) {
      try {
        out.close();
      }
 catch (      IOException ioe) {
      }
    }
  }
  MavenDependencyResolver resolver=DependencyResolvers.use(MavenDependencyResolver.class).configureFrom(settingsXml.getAbsolutePath());
  JavaArchive weldServlet=resolver.artifact("org.jboss.weld.servlet:weld-servlet:1.1.0.Final").resolveAs(JavaArchive.class).iterator().next();
  WebAppDescriptor webFragmentXml=Descriptors.create(WebAppDescriptor.class);
  return weldServlet.addAsManifestResource(new StringAsset(webFragmentXml.createListener().listenerClass("org.jboss.weld.environment.servlet.Listener").up().exportAsString().replaceAll("web-app","web-fragment").replace("<listener>","<name>WeldServlet</name><listener>")),"web-fragment.xml");
}
 

Example 40

From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  31 
vote

/** 
 * 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 {
  if (dirTemp == null) {
    File dir=new File(System.getProperty("java.io.tmpdir"),TMP_SUB_DIRECTORY);
    if (!dir.exists()) {
      dir.mkdir();
    }
    chmod777(dir);
    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);
    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);
  }
}
 

Example 41

From project avro, under directory /lang/java/tools/src/main/java/org/apache/avro/tool/.

Source file: ToTextTool.java

  31 
vote

@Override public int run(InputStream stdin,PrintStream out,PrintStream err,List<String> args) throws Exception {
  OptionParser p=new OptionParser();
  OptionSet opts=p.parse(args.toArray(new String[0]));
  if (opts.nonOptionArguments().size() != 2) {
    err.println("Expected 2 args: from_file to_file (local filenames," + " Hadoop URI's, or '-' for stdin/stdout");
    p.printHelpOn(err);
    return 1;
  }
  BufferedInputStream inStream=Util.fileOrStdin(args.get(0),stdin);
  BufferedOutputStream outStream=Util.fileOrStdout(args.get(1),out);
  GenericDatumReader<Object> reader=new GenericDatumReader<Object>();
  DataFileStream<Object> fileReader=new DataFileStream<Object>(inStream,reader);
  if (!fileReader.getSchema().equals(Schema.parse(TEXT_FILE_SCHEMA))) {
    err.println("Avro file is not generic text schema");
    p.printHelpOn(err);
    return 1;
  }
  while (fileReader.hasNext()) {
    ByteBuffer outBuff=(ByteBuffer)fileReader.next();
    outStream.write(outBuff.array());
    outStream.write(LINE_SEPARATOR);
  }
  outStream.close();
  inStream.close();
  return 0;
}
 

Example 42

From project Backyard-Brains-Android-App, under directory /src/com/backyardbrains/audio/.

Source file: RecordingSaver.java

  31 
vote

/** 
 * Create a the BackyardBrains directory on the sdcard if it doesn't exist, then set up a file output stream in that directory which we'll use to write to later
 * @param filename
 */
private void initializeAndCreateFile(String filename){
  bybDirectory=createBybDirectory();
  mArrayToRecordTo=new ByteArrayOutputStream();
  try {
    bufferedStream=new BufferedOutputStream(mArrayToRecordTo);
  }
 catch (  Exception e) {
    throw new IllegalStateException("Cannot open file for writing",e);
  }
  dataOutputStreamInstance=new DataOutputStream(bufferedStream);
}
 

Example 43

From project BazaarUtils, under directory /src/com/congenialmobile/utils/.

Source file: NetUtils.java

  31 
vote

/** 
 * Retrieve a file from the given url and save it into the given destination file.
 * @param sourceUrl
 * @param dest
 * @param stopperIndicator
 * @return true if successful
 */
public static boolean retrieveAndSave(final URL sourceUrl,final File dest,final StopperIndicator stopperIndicator){
  HttpURLConnection connection;
  try {
    if (DEBUG_NETUTILS)     Log.d(TAG,"retrieveAndSave :: url=" + sourceUrl);
    connection=(HttpURLConnection)sourceUrl.openConnection();
    connection.setConnectTimeout(TIMEOUT_CONNECTION);
    connection.setReadTimeout(TIMEOUT_READ);
    int responseCode=connection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
      InputStream is=connection.getInputStream();
      byte[] buffer=new byte[BUFFER_SIZE_NET];
      if (!dest.getParentFile().exists())       dest.getParentFile().mkdirs();
      BufferedOutputStream fos=new BufferedOutputStream(new FileOutputStream(dest));
      int byteRead;
      while ((byteRead=is.read(buffer)) != -1) {
        if ((stopperIndicator != null) && stopperIndicator.stop)         throw new IOException("Stopped by stopperIndicator");
        fos.write(buffer,0,byteRead);
      }
      fos.close();
      is.close();
      return true;
    }
 else {
      Log.w(TAG,"retrieveAndSave :: responseCode=" + responseCode);
      return false;
    }
  }
 catch (  IOException e) {
    Log.w(TAG,"retrieveAndSave :: IOException",e);
    if (dest.exists())     dest.delete();
    return false;
  }
}
 

Example 44

From project BeeQueue, under directory /src/org/beequeue/util/.

Source file: Buffers.java

  31 
vote

public static BufferedOutputStream bufferOutput(OutputStream os,int bufferSize){
  if (os instanceof BufferedOutputStream) {
    return (BufferedOutputStream)os;
  }
 else {
    return new BufferedOutputStream(os,adjustBufferSize(bufferSize));
  }
}
 

Example 45

From project behemoth, under directory /gate/src/test/java/com/digitalpebble/behemoth/gate/.

Source file: GATEProcessorTest.java

  31 
vote

/** 
 * Unzips the argument into the temp directory and returns the unzipped location.
 */
public static File unzip(File inputZip){
  File rootDir=null;
  try {
    BufferedOutputStream dest=null;
    BufferedInputStream is=null;
    ZipEntry entry;
    ZipFile zipfile=new ZipFile(inputZip);
    String zipname=inputZip.getName().replaceAll("\\.zip","");
    File test=File.createTempFile("aaa","aaa");
    String tempDir=test.getParent();
    test.delete();
    rootDir=new File(tempDir,zipname);
    rootDir.mkdir();
    Enumeration e=zipfile.entries();
    while (e.hasMoreElements()) {
      entry=(ZipEntry)e.nextElement();
      is=new BufferedInputStream(zipfile.getInputStream(entry));
      int count;
      byte data[]=new byte[BUFFER];
      File target=new File(rootDir,entry.getName());
      if (entry.getName().endsWith("/")) {
        target.mkdir();
        continue;
      }
      FileOutputStream fos=new FileOutputStream(target);
      dest=new BufferedOutputStream(fos,BUFFER);
      while ((count=is.read(data,0,BUFFER)) != -1) {
        dest.write(data,0,count);
      }
      dest.flush();
      dest.close();
      is.close();
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return rootDir;
}
 

Example 46

From project Bio-PEPA, under directory /uk.ac.ed.inf.common.ui.plotting/src/uk/ac/ed/inf/common/ui/plotting/internal/.

Source file: PlottingTools.java

  31 
vote

public void write(IChart chart,String path) throws PlottingException {
  Serializer serialiser=SerializerImpl.instance();
  Chart birtChart=((CommonChart)chart).getBirtChart();
  try {
    serialiser.write(birtChart,new BufferedOutputStream(new FileOutputStream(path)));
  }
 catch (  Exception e) {
    IStatus status=new Status(IStatus.ERROR,Plotting.PLUGIN_ID,"Serialisation error",e);
    throw new PlottingException(status);
  }
}
 

Example 47

From project BookmarksPortlet, under directory /src/main/java/edu/wisc/my/portlets/bookmarks/dao/file/.

Source file: FileSystemBookmarkStore.java

  31 
vote

/** 
 * @see edu.wisc.my.portlets.bookmarks.dao.BookmarkStore#storeBookmarkSet(edu.wisc.my.portlets.bookmarks.domain.BookmarkSet)
 */
public void storeBookmarkSet(BookmarkSet bookmarkSet){
  if (bookmarkSet == null) {
    throw new IllegalArgumentException("AddressBook may not be null");
  }
  final File storeFile=this.getStoreFile(bookmarkSet.getOwner(),bookmarkSet.getName());
  try {
    final FileOutputStream fos=new FileOutputStream(storeFile);
    final BufferedOutputStream bos=new BufferedOutputStream(fos);
    final XMLEncoder e=new XMLEncoder(bos);
    try {
      e.writeObject(bookmarkSet);
    }
  finally {
      e.close();
    }
  }
 catch (  FileNotFoundException fnfe) {
    final String errorMsg="Error storing BookmarkSet='" + bookmarkSet + "' to file='"+ storeFile+ "'";
    logger.error(errorMsg,fnfe);
    throw new DataAccessResourceFailureException(errorMsg,fnfe);
  }
}
 

Example 48

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/utils/.

Source file: UtilFile.java

  31 
vote

public static File saveFileToProject(String project,String name,int fileID,Context context,int type){
  String filePath;
  if (project == null || project.equalsIgnoreCase("")) {
    filePath=Utils.buildProjectPath(name);
  }
 else {
switch (type) {
case TYPE_IMAGE_FILE:
      filePath=Utils.buildPath(Utils.buildProjectPath(project),Constants.IMAGE_DIRECTORY,name);
    break;
case TYPE_SOUND_FILE:
  filePath=Utils.buildPath(Utils.buildProjectPath(project),Constants.SOUND_DIRECTORY,name);
break;
default :
filePath=Utils.buildProjectPath(name);
break;
}
}
BufferedInputStream in=new BufferedInputStream(context.getResources().openRawResource(fileID),Constants.BUFFER_8K);
try {
File file=new File(filePath);
file.getParentFile().mkdirs();
file.createNewFile();
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(file),Constants.BUFFER_8K);
byte[] buffer=new byte[Constants.BUFFER_8K];
int length=0;
while ((length=in.read(buffer)) > 0) {
out.write(buffer,0,length);
}
in.close();
out.flush();
out.close();
return file;
}
 catch (IOException e) {
e.printStackTrace();
return null;
}
}
 

Example 49

From project cdi-arq-workshop, under directory /arquillian-showcase/extension-weld-servlet/src/main/java/org/jboss/arquillian/extension/cdi/.

Source file: WeldServletDeploymentAppender.java

  31 
vote

@Override public Archive<?> createAuxiliaryArchive(){
  File settingsXml=null;
  InputStream in=null;
  BufferedOutputStream out=null;
  try {
    settingsXml=File.createTempFile("arquillian-","-settings.xml");
    settingsXml.deleteOnExit();
    in=WeldServletDeploymentAppender.class.getResourceAsStream("jboss-repository-settings.xml");
    out=new BufferedOutputStream(new FileOutputStream(settingsXml));
    byte[] buffer=new byte[1024];
    int len;
    while ((len=in.read(buffer)) != -1) {
      out.write(buffer,0,len);
    }
  }
 catch (  IOException ioe) {
    throw new IllegalStateException("Could not read settings.xml from classpath");
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      IOException ioe) {
      }
    }
    if (out != null) {
      try {
        out.close();
      }
 catch (      IOException ioe) {
      }
    }
  }
  MavenDependencyResolver resolver=DependencyResolvers.use(MavenDependencyResolver.class).configureFrom(settingsXml.getAbsolutePath());
  JavaArchive weldServlet=resolver.artifact("org.jboss.weld.servlet:weld-servlet:1.1.0.Final").resolveAs(JavaArchive.class).iterator().next();
  WebAppDescriptor webFragmentXml=Descriptors.create(WebAppDescriptor.class);
  return weldServlet.addAsManifestResource(new StringAsset(webFragmentXml.listener("org.jboss.weld.environment.servlet.Listener").exportAsString().replaceAll("web-app","web-fragment").replace("<listener>","<name>WeldServlet</name><listener>")),"web-fragment.xml");
}
 

Example 50

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.

Source file: ZipUtilities.java

  31 
vote

public static File readFileFromZipFile(ZipEntry entry,ZipFile zipFile) throws IOException {
  long size=entry.getSize();
  if (size > 0) {
    BufferedInputStream reader=new BufferedInputStream(zipFile.getInputStream(entry));
    String fileName=new File(entry.getName()).getName();
    File outputFile=FileUtilities.createTemporaryFileInDefaultTemporaryDirectory(fileName,"tmp");
    BufferedOutputStream output=new BufferedOutputStream(new FileOutputStream(outputFile),BUFFER_SIZE);
    byte readBytes[]=new byte[BUFFER_SIZE];
    int readByteCount;
    while ((readByteCount=reader.read(readBytes,0,BUFFER_SIZE)) != -1) {
      output.write(readBytes,0,readByteCount);
    }
    output.close();
    return outputFile;
  }
 else {
    return null;
  }
}
 

Example 51

From project com.cedarsoft.serialization, under directory /serializers/commons/src/main/java/com/cedarsoft/serialization/serializers/registry/.

Source file: FileBasedObjectsAccess.java

  31 
vote

@Override @Nonnull public OutputStream openOut(@Nonnull String id) throws FileNotFoundException {
  File file=getFile(id);
  if (file.exists()) {
    throw new StillContainedException(id);
  }
  return new BufferedOutputStream(new FileOutputStream(file));
}
 

Example 52

From project commons-compress, under directory /src/test/java/org/apache/commons/compress/archivers/zip/.

Source file: Zip64SupportIT.java

  31 
vote

private static void withTemporaryArchive(String testName,ZipOutputTest test,boolean useRandomAccessFile) throws Throwable {
  File f=getTempFile(testName);
  BufferedOutputStream os=null;
  ZipArchiveOutputStream zos=useRandomAccessFile ? new ZipArchiveOutputStream(f) : new ZipArchiveOutputStream(os=new BufferedOutputStream(new FileOutputStream(f)));
  try {
    test.test(f,zos);
  }
 catch (  IOException ex) {
    System.err.println("Failed to write archive because of: " + ex.getMessage() + " - likely not enough disk space.");
    assumeTrue(false);
  }
 finally {
    try {
      zos.destroy();
    }
  finally {
      if (os != null) {
        os.close();
      }
      AbstractTestCase.tryHardToDelete(f);
    }
  }
}
 

Example 53

From project community-plugins, under directory /deployit-cli-plugins/dar-manifest-exporter/src/main/java/ext/deployit/community/cli/manifestexport/io/.

Source file: ManifestWriter.java

  31 
vote

public static File write(Manifest manifest,String targetPath) throws IOException {
  File manifestFile=new File(targetPath + '/' + MANIFEST_NAME);
  createParentDirs(manifestFile);
  OutputStream manifestOutput=new BufferedOutputStream(new FileOutputStream(manifestFile));
  try {
    manifest.write(manifestOutput);
  }
  finally {
    manifestOutput.close();
  }
  return manifestFile;
}
 

Example 54

From project connectbot, under directory /src/com/trilead/ssh2/.

Source file: SFTPv3Client.java

  31 
vote

/** 
 * Create a SFTP v3 client.
 * @param conn The underlying SSH-2 connection to be used.
 * @param debug
 * @throws IOException
 * @deprecated this constructor (debug version) will disappear in the future,use  {@link #SFTPv3Client(Connection)} instead.
 */
@Deprecated public SFTPv3Client(Connection conn,PrintStream debug) throws IOException {
  if (conn == null)   throw new IllegalArgumentException("Cannot accept null argument!");
  this.conn=conn;
  this.debug=debug;
  if (debug != null)   debug.println("Opening session and starting SFTP subsystem.");
  sess=conn.openSession();
  sess.startSubSystem("sftp");
  is=sess.getStdout();
  os=new BufferedOutputStream(sess.getStdin(),2048);
  if ((is == null) || (os == null))   throw new IOException("There is a problem with the streams of the underlying channel.");
  init();
}
 

Example 55

From project crammer, under directory /src/main/java/uk/ac/ebi/ena/sra/cram/.

Source file: Bam2Cram.java

  31 
vote

private static OutputStream createOutputStream(File outputCramFile,boolean wrapInGzip) throws IOException {
  OutputStream os=null;
  if (outputCramFile != null) {
    FileOutputStream cramFOS=new FileOutputStream(outputCramFile);
    if (wrapInGzip)     os=new BufferedOutputStream(new GZIPOutputStream(cramFOS));
 else     os=new BufferedOutputStream(cramFOS);
  }
 else   os=new BufferedOutputStream(System.out);
  return os;
}
 

Example 56

From project cw-omnibus, under directory /EmPubLite/T16-Update/src/com/commonsware/empublite/.

Source file: DownloadInstallService.java

  31 
vote

private static void unzip(File src,File dest) throws IOException {
  InputStream is=new FileInputStream(src);
  ZipInputStream zis=new ZipInputStream(new BufferedInputStream(is));
  ZipEntry ze;
  dest.mkdirs();
  while ((ze=zis.getNextEntry()) != null) {
    byte[] buffer=new byte[8192];
    int count;
    FileOutputStream fos=new FileOutputStream(new File(dest,ze.getName()));
    BufferedOutputStream out=new BufferedOutputStream(fos);
    try {
      while ((count=zis.read(buffer)) != -1) {
        out.write(buffer,0,count);
      }
      out.flush();
    }
  finally {
      fos.getFD().sync();
      out.close();
    }
    zis.closeEntry();
  }
  zis.close();
}
 

Example 57

From project daily-money, under directory /dailymoney/src/com/bottleworks/dailymoney/calculator2/.

Source file: Persist.java

  31 
vote

void save(){
  try {
    OutputStream os=new BufferedOutputStream(mContext.openFileOutput(FILE_NAME,0),8192);
    DataOutputStream out=new DataOutputStream(os);
    out.writeInt(LAST_VERSION);
    history.write(out);
    out.close();
  }
 catch (  IOException e) {
    Calculator.log("" + e);
  }
}
 

Example 58

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/job/.

Source file: TaskLog.java

  31 
vote

private static synchronized void writeToIndexFile(String logLocation,boolean isCleanup) throws IOException {
  File tmpIndexFile=getTmpIndexFile(currentTaskid,isCleanup);
  BufferedOutputStream bos=new BufferedOutputStream(SecureIOUtils.createForWrite(tmpIndexFile,0644));
  DataOutputStream dos=new DataOutputStream(bos);
  try {
    dos.writeBytes(LogFileDetail.LOCATION + logLocation + "\n"+ LogName.STDOUT.toString()+ ":");
    dos.writeBytes(Long.toString(prevOutLength) + " ");
    dos.writeBytes(Long.toString(new File(logLocation,LogName.STDOUT.toString()).length() - prevOutLength) + "\n" + LogName.STDERR+ ":");
    dos.writeBytes(Long.toString(prevErrLength) + " ");
    dos.writeBytes(Long.toString(new File(logLocation,LogName.STDERR.toString()).length() - prevErrLength) + "\n" + LogName.SYSLOG.toString()+ ":");
    dos.writeBytes(Long.toString(prevLogLength) + " ");
    dos.writeBytes(Long.toString(new File(logLocation,LogName.SYSLOG.toString()).length() - prevLogLength) + "\n");
    dos.close();
    dos=null;
  }
  finally {
    IOUtils.cleanup(LOG,dos);
  }
  File indexFile=getIndexFile(currentTaskid,isCleanup);
  Path indexFilePath=new Path(indexFile.getAbsolutePath());
  Path tmpIndexFilePath=new Path(tmpIndexFile.getAbsolutePath());
  if (localFS == null) {
    localFS=FileSystem.getLocal(new Configuration());
  }
  localFS.rename(tmpIndexFilePath,indexFilePath);
}
 

Example 59

From project droidparts, under directory /extra/src/org/droidparts/util/io/.

Source file: BitmapCacher.java

  31 
vote

public boolean saveToCache(String name,Bitmap bm){
  File file=new File(cacheDir,getFileName(name));
  BufferedOutputStream bos=null;
  try {
    bos=new BufferedOutputStream(new FileOutputStream(file),BUFFER_SIZE);
    bm.compress(PNG,100,bos);
    return true;
  }
 catch (  Exception e) {
    L.e(e);
    return false;
  }
 finally {
    silentlyClose(bos);
  }
}
 

Example 60

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/.

Source file: DropboxBackupActivity.java

  31 
vote

private boolean downloadDropboxFile(String dbPath,File localFile) throws IOException {
  BufferedInputStream br=null;
  BufferedOutputStream bw=null;
  try {
    if (!localFile.exists()) {
      localFile.createNewFile();
    }
    FileDownload fd=api.getFileStream("dropbox","/" + dbPath,null);
    br=new BufferedInputStream(fd.is);
    bw=new BufferedOutputStream(new FileOutputStream(localFile));
    byte[] buffer=new byte[4096];
    int read;
    while (true) {
      read=br.read(buffer);
      if (read <= 0) {
        break;
      }
      bw.write(buffer,0,read);
    }
  }
  finally {
    if (bw != null) {
      bw.close();
    }
    if (br != null) {
      br.close();
    }
  }
  return true;
}
 

Example 61

From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.

Source file: SaveAsActivity.java

  30 
vote

private void saveFile(File destination){
  InputStream in=null;
  OutputStream out=null;
  try {
    if (fileScheme)     in=new BufferedInputStream(new FileInputStream(source.getPath()));
 else     in=new BufferedInputStream(getContentResolver().openInputStream(source));
    out=new BufferedOutputStream(new FileOutputStream(destination));
    byte[] buffer=new byte[1024];
    while (in.read(buffer) != -1)     out.write(buffer);
    Toast.makeText(this,R.string.saveas_file_saved,Toast.LENGTH_SHORT).show();
  }
 catch (  FileNotFoundException e) {
    Toast.makeText(this,R.string.saveas_error,Toast.LENGTH_SHORT).show();
  }
catch (  IOException e) {
    Toast.makeText(this,R.string.saveas_error,Toast.LENGTH_SHORT).show();
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      IOException e) {
      }
    }
    if (out != null) {
      try {
        out.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 62

From project Application-Builder, under directory /src/main/java/org/silverpeas/applicationbuilder/.

Source file: EARDirectory.java

  30 
vote

/** 
 * Adds an XML file in the archive by the means of streams.
 * @param xmlDoc the XML document to add in the archive
 * @since 1.0
 * @roseuid 3AAF4D630303
 */
public void add(XmlDocument xmlDoc) throws AppBuilderException {
  OutputStream out=null;
  try {
    File entry=getNormalizedEntry(xmlDoc.getLocation());
    out=new BufferedOutputStream(new FileOutputStream(new File(entry,xmlDoc.getName())));
    xmlDoc.saveTo(out);
    out.flush();
  }
 catch (  Exception e) {
    throw new AppBuilderException(getName() + " : impossible to add the document \"" + xmlDoc.getArchivePath()+ "\"",e);
  }
 finally {
    close(out);
  }
}
 

Example 63

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.

Source file: PlatformUtil.java

  30 
vote

/** 
 * Utility to extract a resource file to a user configuration directory, if it does not exist - useful for setting up default configurations.
 * @param resourceClass class in the same package as the resourceFile toextract
 * @param resourceFile resource file name to extract
 * @return true if extracted, false otherwise (if file already exists)
 * @throws IOException exception thrown if extract the file failed for IOreasons
 */
public static boolean extractResourceToUserConfigDir(final Class resourceClass,final String resourceFile) throws IOException {
  final File userDir=new File(getUserConfigDirectory());
  final File resourceFileF=new File(userDir + File.separator + resourceFile);
  if (resourceFileF.exists()) {
    return false;
  }
  InputStream inputStream=resourceClass.getResourceAsStream(resourceFile);
  OutputStream out=null;
  InputStream in=null;
  try {
    in=new BufferedInputStream(inputStream);
    OutputStream outFile=new FileOutputStream(resourceFileF);
    out=new BufferedOutputStream(outFile);
    int readBytes=0;
    while ((readBytes=in.read()) != -1) {
      out.write(readBytes);
    }
  }
  finally {
    if (in != null) {
      in.close();
    }
    if (out != null) {
      out.flush();
      out.close();
    }
  }
  return true;
}
 

Example 64

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/xml/.

Source file: Processor.java

  30 
vote

public static void main(final String[] args) throws Exception {
  if (args.length < 2) {
    showUsage();
    return;
  }
  int inRepresentation=getRepresentation(args[0]);
  int outRepresentation=getRepresentation(args[1]);
  InputStream is=System.in;
  OutputStream os=new BufferedOutputStream(System.out);
  Source xslt=null;
  for (int i=2; i < args.length; i++) {
    if ("-in".equals(args[i])) {
      is=new FileInputStream(args[++i]);
    }
 else     if ("-out".equals(args[i])) {
      os=new BufferedOutputStream(new FileOutputStream(args[++i]));
    }
 else     if ("-xslt".equals(args[i])) {
      xslt=new StreamSource(new FileInputStream(args[++i]));
    }
 else {
      showUsage();
      return;
    }
  }
  if (inRepresentation == 0 || outRepresentation == 0) {
    showUsage();
    return;
  }
  Processor m=new Processor(inRepresentation,outRepresentation,is,os,xslt);
  long l1=System.currentTimeMillis();
  int n=m.process();
  long l2=System.currentTimeMillis();
  System.err.println(n);
  System.err.println("" + (l2 - l1) + "ms  "+ 1000f * n / (l2 - l1) + " resources/sec");
}
 

Example 65

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionSCM.java

  30 
vote

/** 
 * Called after checkout/update has finished to compute the changelog.
 */
private boolean calcChangeLog(AbstractBuild<?,?> build,File changelogFile,BuildListener listener,List<External> externals) throws IOException, InterruptedException {
  if (build.getPreviousBuild() == null) {
    return createEmptyChangeLog(changelogFile,listener,"log");
  }
  OutputStream os=new BufferedOutputStream(new FileOutputStream(changelogFile));
  boolean created;
  try {
    created=new BlameSubversionChangeLogBuilder(build,listener,this).run(externals,new StreamResult(os));
  }
  finally {
    os.close();
  }
  if (!created)   createEmptyChangeLog(changelogFile,listener,"log");
  return true;
}
 

Example 66

From project BombusLime, under directory /src/org/bombusim/lime/data/.

Source file: Vcard.java

  30 
vote

private void saveAvatar(){
  if (photoHash.equals(AVATAR_MISSING))   return;
  if (photoHash.equals(AVATAR_PENDING))   return;
  Context context=Lime.getInstance().getApplicationContext();
  String fn="avatar" + photoHash + ".png";
  OutputStream os=null;
  try {
    File cache=context.getCacheDir();
    File f=new File(cache,fn);
    if (!f.createNewFile())     return;
    os=new BufferedOutputStream(new FileOutputStream(f));
    avatar.compress(CompressFormat.PNG,0,os);
    os.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
 finally {
    if (os != null)     try {
      os.close();
    }
 catch (    Exception ex) {
      ex.printStackTrace();
    }
  }
}
 

Example 67

From project Cafe, under directory /webapp/src/org/openqa/selenium/io/.

Source file: Zip.java

  30 
vote

public void unzipFile(File output,InputStream zipStream,String name) throws IOException {
  File toWrite=new File(output,name);
  if (!FileHandler.createDir(toWrite.getParentFile()))   throw new IOException("Cannot create parent director for: " + name);
  OutputStream out=new BufferedOutputStream(new FileOutputStream(toWrite),BUF_SIZE);
  try {
    byte[] buffer=new byte[BUF_SIZE];
    int read;
    while ((read=zipStream.read(buffer)) != -1) {
      out.write(buffer,0,read);
    }
  }
  finally {
    out.close();
  }
}
 

Example 68

From project cider, under directory /src/net/yacy/cider/util/.

Source file: FileUtils.java

  30 
vote

public static void saveSet(final File file,final String format,final Set<byte[]> set,final String sep) throws IOException {
  final File tf=new File(file.toString() + ".prt" + (System.currentTimeMillis() % 1000));
  OutputStream os=null;
  if ((format == null) || (format.equals("plain"))) {
    os=new BufferedOutputStream(new FileOutputStream(tf));
  }
 else   if (format.equals("gzip")) {
    os=new GZIPOutputStream(new FileOutputStream(tf));
  }
 else   if (format.equals("zip")) {
    final ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(file));
    String name=file.getName();
    if (name.endsWith(".zip"))     name=name.substring(0,name.length() - 4);
    zos.putNextEntry(new ZipEntry(name + ".txt"));
    os=zos;
  }
  if (os != null) {
    for (final Iterator<byte[]> i=set.iterator(); i.hasNext(); ) {
      os.write(i.next());
      if (sep != null)       os.write(sep.getBytes("UTF-8"));
    }
    os.close();
  }
  forceMove(tf,file);
}
 

Example 69

From project citrus-sample, under directory /petstore/biz/src/main/java/com/alibaba/sample/petstore/biz/impl/.

Source file: StoreManagerImpl.java

  30 
vote

private String getPictureName(FileItem picture) throws IOException {
  String imageFileName=null;
  if (picture != null) {
    String fileName=picture.getName().replace('\\','/');
    fileName=fileName.substring(fileName.lastIndexOf("/") + 1);
    String ext="";
    int index=fileName.lastIndexOf(".");
    if (index > 0) {
      ext=fileName.substring(index);
    }
    File imageFile=File.createTempFile("image_",ext,uploadDir);
    imageFileName=imageFile.getName();
    InputStream is=picture.getInputStream();
    OutputStream os=new BufferedOutputStream(new FileOutputStream(imageFile));
    StreamUtil.io(is,os,true,true);
  }
  return imageFileName;
}
 

Example 70

From project cloudify, under directory /CLI/src/main/java/org/cloudifysource/shell/commands/.

Source file: TestRecipe.java

  30 
vote

/** 
 * Unzips a given file.
 * @param inputFile The zip file to extract
 * @return The new folder, containing the extracted content of the zip file
 * @throws IOException Reporting a failure to extract the zipped file or close it afterwards
 */
private static File unzipFile(final File inputFile) throws IOException {
  ZipFile zipFile=null;
  try {
    final File baseDir=TestRecipe.createTempDir();
    zipFile=new ZipFile(inputFile);
    final Enumeration<? extends ZipEntry> entries=zipFile.entries();
    while (entries.hasMoreElements()) {
      final ZipEntry entry=entries.nextElement();
      if (entry.isDirectory()) {
        logger.fine("Extracting directory: " + entry.getName());
        final File dir=new File(baseDir,entry.getName());
        dir.mkdir();
        continue;
      }
      logger.finer("Extracting file: " + entry.getName());
      final File file=new File(baseDir,entry.getName());
      file.getParentFile().mkdirs();
      ServiceReader.copyInputStream(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(file)));
    }
    return baseDir;
  }
  finally {
    if (zipFile != null) {
      try {
        zipFile.close();
      }
 catch (      final IOException e) {
        logger.log(Level.SEVERE,"Failed to close zip file after unzipping zip contents",e);
      }
    }
  }
}
 

Example 71

From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/local/.

Source file: JPPFLocalNode.java

  30 
vote

private void unzipNode(InputStream fileToUnzip,File targetDir){
  ZipInputStream zipFile;
  try {
    zipFile=new ZipInputStream(fileToUnzip);
    ZipEntry entry;
    while ((entry=zipFile.getNextEntry()) != null) {
      if (entry.isDirectory()) {
        System.err.println("Extracting directory: " + entry.getName());
        (new File(targetDir,entry.getName())).mkdir();
        continue;
      }
      System.err.println("Extracting file: " + entry.getName());
      File targetFile=new File(targetDir,entry.getName());
      copyInputStream_notClosing(zipFile,new BufferedOutputStream(new FileOutputStream(targetFile)));
    }
    zipFile.close();
  }
 catch (  IOException ioe) {
    logger.warn("Unhandled exception.",ioe);
  }
}
 

Example 72

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/.

Source file: ShellConfig.java

  30 
vote

public void loadHistory(final ShellImpl shell){
  File configDir=environment.getConfigDirectory().getUnderlyingResourceObject();
  if ((configDir != null) && configDir.exists() && !shell.isNoInitMode()) {
    File historyFile=new File(configDir.getPath(),ShellImpl.FORGE_COMMAND_HISTORY_FILE);
    try {
      if (!historyFile.exists()) {
        if (!historyFile.createNewFile()) {
          System.err.println("could not create config file: " + historyFile.getAbsolutePath());
        }
      }
    }
 catch (    IOException e) {
      throw new RuntimeException("could not create config file: " + historyFile.getAbsolutePath());
    }
    List<String> history=new ArrayList<String>();
    try {
      BufferedReader reader=new BufferedReader(new FileReader(historyFile));
      String line;
      while ((line=reader.readLine()) != null) {
        history.add(line);
      }
      reader.close();
      shell.setHistory(history);
    }
 catch (    IOException e) {
      throw new RuntimeException("error loading file: " + historyFile.getAbsolutePath());
    }
    try {
      shell.setHistoryOutputStream(new BufferedOutputStream(new FileOutputStream(historyFile,true)));
    }
 catch (    FileNotFoundException e) {
      throw new RuntimeException("error setting forge history output stream to file: " + historyFile.getAbsolutePath());
    }
  }
}
 

Example 73

From project cpp-maven-plugins, under directory /cpp-compiler-maven-plugin/src/main/java/com/ericsson/tools/cpp/compiler/dependencies/.

Source file: DependencyExtractor.java

  30 
vote

private void writeFile(final ZipFile zipFile,final ZipEntry entry,final File targetFile) throws MojoExecutionException {
  InputStream in;
  try {
    in=zipFile.getInputStream(entry);
    final OutputStream out=new BufferedOutputStream(new FileOutputStream(targetFile));
    byte[] buffer=new byte[1024];
    int bufferLength;
    while ((bufferLength=in.read(buffer)) >= 0)     out.write(buffer,0,bufferLength);
    in.close();
    out.close();
    targetFile.setReadOnly();
  }
 catch (  IOException e) {
    throw new MojoExecutionException("Failed to extract " + entry.getName() + " from "+ zipFile.getName()+ " to "+ targetFile.getPath(),e);
  }
}
 

Example 74

From project dawn-ui, under directory /org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/printing/.

Source file: PlotExportPrintUtil.java

  30 
vote

private static void savePostScript(File imageFile,Image image) throws FileNotFoundException {
  ByteArrayOutputStream os=new ByteArrayOutputStream();
  RenderedImage awtImage=convertToAWT(image.getImageData());
  try {
    ImageIO.write(awtImage,"png",os);
  }
 catch (  IOException e) {
    logger.error("Could not write to OutputStream",e);
  }
  try {
    ByteArrayInputStream inputStream=new ByteArrayInputStream(os.toByteArray());
    InputStream is=new BufferedInputStream(inputStream);
    OutputStream fos=new BufferedOutputStream(new FileOutputStream(imageFile.getAbsolutePath()));
    DocFlavor flavor=DocFlavor.INPUT_STREAM.GIF;
    StreamPrintServiceFactory[] factories=StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
    if (factories.length > 0) {
      StreamPrintService service=factories[0].getPrintService(fos);
      DocPrintJob job=service.createPrintJob();
      Doc doc=new SimpleDoc(is,flavor,null);
      PrintJobWatcher pjDone=new PrintJobWatcher(job);
      job.print(doc,null);
      pjDone.waitUntilDone();
    }
    is.close();
    fos.close();
  }
 catch (  PrintException e) {
    logger.error("Could not print to PostScript",e);
  }
catch (  IOException e) {
    logger.error("IO error",e);
  }
}
 

Example 75

From project droolsjbpm-integration, under directory /drools-container/drools-spring/src/test/java/org/drools/container/spring/beans/persistence/.

Source file: JPASingleSessionCommandServiceFactoryEnvTest.java

  30 
vote

public static void writePackage(Package pkg,File dest){
  dest.deleteOnExit();
  OutputStream out=null;
  try {
    out=new BufferedOutputStream(new FileOutputStream(dest));
    DroolsStreamUtils.streamOut(out,pkg);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
 finally {
    if (out != null) {
      try {
        out.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 76

From project EasySOA, under directory /easysoa-registry/easysoa-registry-api/easysoa-registry-api-frascati/src/main/java/org/easysoa/registry/frascati/.

Source file: FileUtils.java

  30 
vote

/** 
 * Unzips the given jar in a temp file and returns its files' URLs Inspired from AssemblyFactoryManager.processContribution() (though doesn't add it to the classloader or parse composites) TODO move to util TODO better : delete temp files afterwards (or mark them so) OR rather use jar:url ?
 * @param SCA zip or jar
 * @return unzipped composites URLs
 * @throws ManagerException
 */
public static final Set<URL> unzipAndGetFileUrls(File file){
  try {
    ZipFile zipFile=new ZipFile(file);
    final String folder=zipFile.getName().substring(zipFile.getName().lastIndexOf(File.separator),zipFile.getName().length() - ".zip".length());
    Set<URL> fileURLSet=new HashSet<URL>();
    final String tempDir=System.getProperty("java.io.tmpdir") + File.separator + folder+ File.separator;
    Enumeration<? extends ZipEntry> entries=zipFile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry=entries.nextElement();
      log.info("ZIP entry: " + entry.getName());
      if (entry.isDirectory()) {
        log.info("create directory : " + tempDir + entry.getName());
        new File(tempDir,entry.getName()).mkdirs();
      }
 else {
        File f=new File(tempDir,File.separator + entry.getName());
        int idx=entry.getName().lastIndexOf(File.separator);
        if (idx != -1) {
          String tmp=entry.getName().substring(0,idx);
          log.info("create directory : " + tempDir + tmp);
          new File(tempDir,tmp).mkdirs();
        }
        copy(zipFile.getInputStream(entry),new BufferedOutputStream(new FileOutputStream(f)));
        fileURLSet.add(f.toURI().toURL());
      }
    }
    return fileURLSet;
  }
 catch (  IOException e) {
    log.error(e);
    return new HashSet<URL>(0);
  }
}
 

Example 77

From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/zip/.

Source file: Zip.java

  29 
vote

/** 
 * Instantiates a new zip.
 * @param in_zipFileLocation the in_zip file location
 */
public Zip(String in_zipFileLocation){
  zipFileLocation=in_zipFileLocation;
  try {
    dest=new FileOutputStream(zipFileLocation);
  }
 catch (  FileNotFoundException e) {
    e.printStackTrace();
  }
  checksum=new CheckedOutputStream(dest,new Adler32());
  out=new ZipOutputStream(new BufferedOutputStream(checksum));
}
 

Example 78

From project and-bible, under directory /jsword-tweaks/src/util/java/net/andbible/util/.

Source file: MJDIndexAll.java

  29 
vote

private void createZipFile(File jarFile,File sourceDir){
  try {
    BufferedInputStream origin=null;
    FileOutputStream dest=new FileOutputStream(jarFile);
    ZipOutputStream out=new ZipOutputStream(new BufferedOutputStream(dest));
    byte data[]=new byte[JAR_BUFFER_SIZE];
    File files[]=sourceDir.listFiles();
    for (int i=0; i < files.length; i++) {
      System.out.println("Adding: " + files[i]);
      FileInputStream fi=new FileInputStream(files[i]);
      origin=new BufferedInputStream(fi,JAR_BUFFER_SIZE);
      ZipEntry entry=new ZipEntry(files[i].getName());
      out.putNextEntry(entry);
      int count;
      while ((count=origin.read(data,0,JAR_BUFFER_SIZE)) != -1) {
        out.write(data,0,count);
      }
      origin.close();
    }
    out.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 79

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/runtime/internal/.

Source file: IOHelper.java

  29 
vote

public static List<String> pack(File sourceDir,File targetZipFile,ProgressMonitor pm) throws IOException, CanceledException {
  if (!sourceDir.exists()) {
    throw new FileNotFoundException(sourceDir.getPath());
  }
  DirScanner dirScanner=new DirScanner(sourceDir,true,true);
  String[] entryNames=dirScanner.scan();
  ZipOutputStream zipOutputStream=new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetZipFile)));
  zipOutputStream.setMethod(ZipEntry.DEFLATED);
  pm.beginTask(MessageFormat.format("Packing {0} into {1}",sourceDir.getName(),targetZipFile.getName()),entryNames.length);
  ArrayList<String> entries=new ArrayList<String>(entryNames.length);
  try {
    for (    String entryName : entryNames) {
      checkIOTaskCanceled(pm);
      ZipEntry zipEntry=new ZipEntry(entryName.replace('\\','/'));
      pm.setSubTaskName(entryName);
      File sourceFile=new File(sourceDir,entryName);
      FileInputStream inputStream=new FileInputStream(sourceFile);
      try {
        zipOutputStream.putNextEntry(zipEntry);
        copy(inputStream,zipOutputStream,entryName,(int)sourceFile.length(),SubProgressMonitor.create(pm,1));
        zipOutputStream.closeEntry();
        entries.add(entryName);
      }
  finally {
        inputStream.close();
      }
    }
    return entries;
  }
  finally {
    pm.done();
    zipOutputStream.close();
  }
}
 

Example 80

From project ceylon-ide-eclipse, under directory /plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/builder/.

Source file: ExplodingJavaFileObject.java

  29 
vote

@Override public OutputStream openOutputStream() throws IOException {
  return new OutputStream(){
    final OutputStream jarStream=javaFileObject.openOutputStream();
    final OutputStream classFileStream=new BufferedOutputStream(new FileOutputStream(classFile));
    @Override public void write(    int b) throws IOException {
      jarStream.write(b);
      classFileStream.write(b);
    }
    @Override public void write(    byte[] b,    int off,    int len) throws IOException {
      jarStream.write(b,off,len);
      classFileStream.write(b,off,len);
    }
    @Override public void write(    byte[] b) throws IOException {
      jarStream.write(b);
      classFileStream.write(b);
    }
    @Override public void close() throws IOException {
      classFileStream.close();
      jarStream.close();
    }
    @Override public void flush() throws IOException {
      classFileStream.flush();
      jarStream.flush();
    }
  }
;
}
 

Example 81

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/agent/.

Source file: AgentControlSocketListener.java

  29 
vote

public void run(){
  try {
    InputStream in=connection.getInputStream();
    BufferedReader br=new BufferedReader(new InputStreamReader(in));
    PrintStream out=new PrintStream(new BufferedOutputStream(connection.getOutputStream()));
    String cmd=null;
    while ((cmd=br.readLine()) != null) {
      processCommand(cmd,out);
    }
    connection.close();
    if (log.isDebugEnabled()) {
      log.debug("control connection closed");
    }
  }
 catch (  SocketException e) {
    if (e.getMessage().equals("Socket Closed"))     log.info("control socket closed");
  }
catch (  IOException e) {
    log.warn("a control connection broke",e);
    try {
      connection.close();
    }
 catch (    Exception ex) {
      log.debug(ExceptionUtil.getStackTrace(ex));
    }
  }
}
 

Example 82

From project ciel-java, under directory /examples/kmeans/src/java/skywriting/examples/kmeans/.

Source file: KMeansDataGenerator.java

  29 
vote

@Override public void invoke() throws Exception {
  double minValue=-1000000.0;
  double maxValue=1000000.0;
  WritableReference out=Ciel.RPC.getOutputFilename(0);
  DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(out.open(),1048576));
  Random rand=new Random(this.seed);
  for (int i=0; i < this.numVectors; ++i) {
    for (int j=0; j < this.numDimensions; ++j) {
      dos.writeDouble((rand.nextDouble() * (maxValue - minValue)) + minValue);
    }
  }
  dos.close();
}
 

Example 83

From project Cloud9, under directory /src/dist/edu/umd/hooka/alignment/.

Source file: HadoopAlign.java

  29 
vote

public void run(JobConf job,Reporter reporter) throws IOException {
  Path outputPath=null;
  Path ttablePath=null;
  Path atablePath=null;
  HadoopAlignConfig hac=null;
  JobConf xjob=null;
  xjob=job;
  hac=new HadoopAlignConfig(job);
  ttablePath=hac.getTTablePath();
  atablePath=hac.getATablePath();
  outputPath=new Path(job.get(TTABLE_ITERATION_OUTPUT));
  IntWritable k=new IntWritable();
  PartialCountContainer t=new PartialCountContainer();
  FileSystem fileSys=FileSystem.get(xjob);
  fileSys.delete(outputPath.suffix("/_logs"),true);
  SequenceFile.Reader[] readers=SequenceFileOutputFormat.getReaders(xjob,outputPath);
  FileReaderZip z=new FileReaderZip(readers);
  TTable tt=new TTable_monolithic_IFAs(fileSys,ttablePath,false);
  boolean emittedATable=false;
  while (z.next(k,t)) {
    if (t.getType() == PartialCountContainer.CONTENT_ARRAY) {
      tt.set(k.get(),(IndexedFloatArray)t.getContent());
      if (k.get() % 1000 == 0)       reporter.progress();
      reporter.incrCounter(MergeCounters.EWORDS,1);
      reporter.incrCounter(MergeCounters.STATISTICS,((IndexedFloatArray)t.getContent()).size() + 1);
    }
 else {
      if (emittedATable)       throw new RuntimeException("Should only have a single ATable!");
      ATable at=(ATable)t.getContent();
      fileSys.delete(atablePath,true);
      DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(fileSys.create(atablePath)));
      at.write(dos);
      dos.close();
      emittedATable=true;
    }
  }
  fileSys.delete(ttablePath,true);
  tt.write();
}
 

Example 84

From project components, under directory /common/rules/src/main/java/org/switchyard/component/common/rules/util/drools/.

Source file: Packages.java

  29 
vote

/** 
 * Writes a Drools KnowledgePackage to File.
 * @param kpkg the KnowledgePackage
 * @param dest the File
 * @throws IOException oops
 */
public static void write(KnowledgePackage kpkg,File dest) throws IOException {
  ObjectOutputStream oos=null;
  try {
    oos=new DroolsObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
    oos.writeObject(kpkg);
  }
  finally {
    if (oos != null) {
      try {
        oos.flush();
        oos.close();
      }
 catch (      Throwable t) {
        t.getMessage();
      }
    }
  }
}
 

Example 85

From project cornerstone, under directory /frameworks/base/services/java/com/android/server/am/.

Source file: ActivityManagerService.java

  29 
vote

private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list){
  File file=getCalledPreBootReceiversFile();
  FileOutputStream fos=null;
  DataOutputStream dos=null;
  try {
    Slog.i(TAG,"Writing new set of last done pre-boot receivers...");
    fos=new FileOutputStream(file);
    dos=new DataOutputStream(new BufferedOutputStream(fos,2048));
    dos.writeInt(LAST_DONE_VERSION);
    dos.writeUTF(android.os.Build.VERSION.RELEASE);
    dos.writeUTF(android.os.Build.VERSION.CODENAME);
    dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
    dos.writeInt(list.size());
    for (int i=0; i < list.size(); i++) {
      dos.writeUTF(list.get(i).getPackageName());
      dos.writeUTF(list.get(i).getClassName());
    }
  }
 catch (  IOException e) {
    Slog.w(TAG,"Failure writing last done pre-boot receivers",e);
    file.delete();
  }
 finally {
    FileUtils.sync(fos);
    if (dos != null) {
      try {
        dos.close();
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
    }
  }
}
 

Example 86

From project CraftMania, under directory /CraftMania/src/org/craftmania/world/.

Source file: ChunkIO.java

  29 
vote

protected void saveChunk(Chunk blockChunk) throws Exception {
  File file=getChunkFile(blockChunk.getX(),blockChunk.getZ());
  DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
  dos.writeBoolean(blockChunk.isGenerated());
  System.out.println("Save Chunk (" + blockChunk.getX() + ", "+ blockChunk.getZ()+ "): generated = "+ blockChunk.isGenerated());
  ChunkData data=blockChunk.getChunkData();
  int blockCount=0;
  for (int i=0; i < Chunk.BLOCK_COUNT; ++i) {
    byte b=data.getBlockType(i);
    if (b != 0) {
      blockCount=i;
    }
  }
  blockCount++;
  dos.writeInt(blockCount);
  for (int i=0; i < blockCount; ++i) {
    byte b=data.getBlockType(i);
    if (data.isSpecial(i)) {
      Block bl=data.getSpecialBlock(i);
      BlockType type=_blockManager.getBlockType(b);
      dos.writeByte(b);
      dos.writeByte(bl.getMetaData());
      if (type.hasSpecialSaveData()) {
        bl.saveSpecialSaveData(dos);
      }
    }
 else     if (b == 0) {
      dos.writeShort(0);
    }
 else {
      dos.writeByte(b);
      dos.writeByte(data.getMetaData(i));
    }
  }
  dos.flush();
  dos.close();
}