java.io.BufferedOutputStream Java Examples

The following examples show how to use java.io.BufferedOutputStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CompressTools.java    From MyBox with Apache License 2.0 7 votes vote down vote up
public static File decompress(CompressorInputStream compressorInputStream, File targetFile) {
        try {
            if (compressorInputStream == null) {
                return null;
            }
            File file = (targetFile == null) ? FileTools.getTempFile() : targetFile;
            if (file.exists()) {
                file.delete();
            }
            try ( BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
                final byte[] buf = new byte[CommonValues.IOBufferLength];
                int len = -1;
                while (-1 != (len = compressorInputStream.read(buf))) {
                    out.write(buf, 0, len);
                }
            }
            return file;
        } catch (Exception e) {
//            logger.debug(e.toString());
            return null;
        }
    }
 
Example #2
Source File: ZipUtilities.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Zip a bytearray
 * 
 * @param data
 * @return
 * @throws IOException
 */
public static byte[] zip(byte[] data, String entryFileName) throws IOException {
	try(final ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
		try(final ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outStream))) {
			
			if (data != null) {
				addFileDataToOpenZipFileStream(data, entryFileName, zipOutputStream);
			}
			
		}
		
		outStream.flush();
		
		return outStream.toByteArray();
	}
}
 
Example #3
Source File: ZipUtil.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
public static void decompress(final String sourceFile, final String outputDir, final Checksum checksum)
                                                                                                       throws IOException {
    try (final FileInputStream fis = new FileInputStream(sourceFile);
            final CheckedInputStream cis = new CheckedInputStream(fis, checksum);
            final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(cis))) {
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            final String fileName = entry.getName();
            final File entryFile = new File(Paths.get(outputDir, fileName).toString());
            FileUtils.forceMkdir(entryFile.getParentFile());
            try (final FileOutputStream fos = new FileOutputStream(entryFile);
                    final BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                IOUtils.copy(zis, bos);
                bos.flush();
                fos.getFD().sync();
            }
        }
        // Continue to read all remaining bytes(extra metadata of ZipEntry) directly from the checked stream,
        // Otherwise, the checksum value maybe unexpected.
        //
        // See https://coderanch.com/t/279175/java/ZipInputStream
        IOUtils.copy(cis, NullOutputStream.NULL_OUTPUT_STREAM);
    }
}
 
Example #4
Source File: Injector.java    From deployment-examples with MIT License 6 votes vote down vote up
/** Publish generated events to a file. */
public static void publishDataToFile(String fileName, int numMessages, int delayInMillis)
    throws IOException {
  PrintWriter out =
      new PrintWriter(
          new OutputStreamWriter(
              new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8"));

  try {
    for (int i = 0; i < Math.max(1, numMessages); i++) {
      Long currTime = System.currentTimeMillis();
      String message = generateEvent(currTime, delayInMillis);
      out.println(message);
    }
  } catch (Exception e) {
    System.err.print("Error in writing generated events to file");
    e.printStackTrace();
  } finally {
    out.flush();
    out.close();
  }
}
 
Example #5
Source File: VisualGraphTopComponent.java    From constellation with Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground() throws Exception {
    final ReadableGraph rg = graph.getReadableGraph();
    try {
        copy = rg.copy();
    } finally {
        rg.release();
    }
    try {
        try (OutputStream out = new BufferedOutputStream(freshGdo.getPrimaryFile().getOutputStream())) {
            // Write the graph.
            cancelled = new GraphJsonWriter().writeGraphToZip(copy, out, new HandleIoProgress("Writing..."));
        }
        SaveNotification.saved(freshGdo.getPrimaryFile().getPath());
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }

    return null;
}
 
Example #6
Source File: FileUtil.java    From FaceDemo with Apache License 2.0 6 votes vote down vote up
/**
 * 保存一个暂时的bitmap图片
 *
 * 保存目录在
 * @param b
 */
public static String saveTmpBitmap(Bitmap b,String name){
    String result= "";
    String jpegName = MyConfig.ROOT_CACHE+File.separator+MyConfig.FACE_DIR +File.separator+name +".jpg";
    Log.d("FileUtil",jpegName);
    result = jpegName;
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100 , bos);
        bos.flush();
        bos.close();
        Log.i(TAG, "暂存的 saveBitmap成功");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.i(TAG, "暂存的saveBitmap失败");
        e.printStackTrace();
    }
    return result;
}
 
Example #7
Source File: BandStructure.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static OutputStream getDumpStream(String name, int seq, String ext, Object b) throws IOException {
    if (dumpDir == null) {
        dumpDir = File.createTempFile("BD_", "", new File("."));
        dumpDir.delete();
        if (dumpDir.mkdir())
            Utils.log.info("Dumping bands to "+dumpDir);
    }
    name = name.replace('(', ' ').replace(')', ' ');
    name = name.replace('/', ' ');
    name = name.replace('*', ' ');
    name = name.trim().replace(' ','_');
    name = ((10000+seq) + "_" + name).substring(1);
    File dumpFile = new File(dumpDir, name+ext);
    Utils.log.info("Dumping "+b+" to "+dumpFile);
    return new BufferedOutputStream(new FileOutputStream(dumpFile));
}
 
Example #8
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void save() {
    final FileOutputStream os;
    try {
        os = mAtomicFile.startWrite();
        boolean success = false;
        try {
            XmlSerializer serializer = new FastXmlSerializer();
            serializer.setOutput(new BufferedOutputStream(os), StandardCharsets.UTF_8.name());
            saveToXml(serializer);
            serializer.flush();
            success = true;
        } finally {
            if (success) {
                mAtomicFile.finishWrite(os);
            } else {
                mAtomicFile.failWrite(os);
            }
        }
    } catch (IOException ex) {
        Slog.w(InputManagerService.TAG, "Failed to save input manager persistent store data.", ex);
    }
}
 
Example #9
Source File: FileUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 保存文件
 * @param file 文件
 * @param data 待存储数据
 * @return {@code true} success, {@code false} fail
 */
public static boolean saveFile(final File file, final byte[] data) {
    if (file != null && data != null) {
        try {
            // 防止文件夹没创建
            createFolder(getDirName(file));
            // 写入文件
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(data);
            bos.close();
            fos.close();
            return true;
        } catch (Exception e) {
            JCLogUtils.eTag(TAG, e, "saveFile");
        }
    }
    return false;
}
 
Example #10
Source File: FileUtil.java    From EasyPhotos with Apache License 2.0 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "IMG_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #11
Source File: FileUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 保存文件
 * @param file 文件
 * @param data 待存储数据
 * @return {@code true} success, {@code false} fail
 */
public static boolean saveFile(final File file, final byte[] data) {
    if (file != null && data != null) {
        try {
            // 防止文件夹没创建
            createFolder(getDirName(file));
            // 写入文件
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(data);
            bos.close();
            fos.close();
            return true;
        } catch (Exception e) {
            JCLogUtils.eTag(TAG, e, "saveFile");
        }
    }
    return false;
}
 
Example #12
Source File: FileHelper.java    From imsdk-android with MIT License 6 votes vote down vote up
public static boolean inputStreamToFile(InputStream inputStream, String filename, String tmpSuffix) throws IOException {

        BufferedInputStream bis = new BufferedInputStream(inputStream);
        // 存储加临时后缀,避免重名
        File file = new File(filename + tmpSuffix);
        File parent = file.getParentFile();
        if (parent != null && (!parent.exists())) {
            parent.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos, CACHED_SIZE);
        int count;
        byte data[] = new byte[CACHED_SIZE];
        while ((count = bis.read(data, 0, CACHED_SIZE)) != -1) {
            bos.write(data, 0, count);
        }
        bos.flush();
        bos.close();
        bis.close();

        return renameFile(file, filename);
    }
 
Example #13
Source File: LruDiskCache.java    From candybar with Apache License 2.0 6 votes vote down vote up
@Override
public boolean save(String imageUri, Bitmap bitmap) throws IOException {
    DiskLruCache.Editor editor = cache.edit(getKey(imageUri));
    if (editor == null) {
        return false;
    }

    OutputStream os = new BufferedOutputStream(editor.newOutputStream(0), bufferSize);
    boolean savedSuccessfully = false;
    try {
        savedSuccessfully = bitmap.compress(compressFormat, compressQuality, os);
    } finally {
        IoUtils.closeSilently(os);
    }
    if (savedSuccessfully) {
        editor.commit();
    } else {
        editor.abort();
    }
    return savedSuccessfully;
}
 
Example #14
Source File: FileUtil.java    From AlbumCameraRecorder with MIT License 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "picture_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #15
Source File: BinaryDictionaryFileDumper.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Copies the data in an input stream to a target file if the magic number matches.
 *
 * If the magic number does not match the expected value, this method throws an
 * IOException. Other usual conditions for IOException or FileNotFoundException
 * also apply.
 *
 * @param input the stream to be copied.
 * @param output an output stream to copy the data to.
 */
public static void checkMagicAndCopyFileTo(final BufferedInputStream input,
        final BufferedOutputStream output) throws IOException {
    // Check the magic number
    final int length = MAGIC_NUMBER_VERSION_2.length;
    final byte[] magicNumberBuffer = new byte[length];
    final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length);
    if (readMagicNumberSize < length) {
        throw new IOException("Less bytes to read than the magic number length");
    }
    if (SHOULD_VERIFY_MAGIC_NUMBER) {
        if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) {
            if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) {
                throw new IOException("Wrong magic number for downloaded file");
            }
        }
    }
    output.write(magicNumberBuffer);

    // Actually copy the file
    final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
    for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer)) {
        output.write(buffer, 0, readBytes);
    }
    input.close();
}
 
Example #16
Source File: ImportTask.java    From apkextractor with GNU General Public License v3.0 6 votes vote down vote up
private void unZipToFile(ZipInputStream zipInputStream,String entryPath) throws Exception{
    File folder=new File(StorageUtil.getMainExternalStoragePath()+"/"+entryPath.substring(0,entryPath.lastIndexOf("/")));
    if(!folder.exists())folder.mkdirs();
    String writePath=StorageUtil.getMainExternalStoragePath()+"/"+entryPath;
    File writeFile=new File(writePath);
    OutputStream outputStream=new BufferedOutputStream(new FileOutputStream(writeFile));
    currentWritePath=writePath;
    currentWrtingFileItem=new FileItem(writeFile);
    byte [] buffer=new byte[1024];
    int len;
    while ((len=zipInputStream.read(buffer))!=-1&&!isInterrupted){
        outputStream.write(buffer,0,len);
        progress+=len;
        checkSpeedAndPostToCallback(len);
        checkProgressAndPostToCallback();
    }
    outputStream.flush();
    outputStream.close();
    if(!isInterrupted)currentWrtingFileItem=null;
}
 
Example #17
Source File: GeneralConfMaker.java    From yosegi with Apache License 2.0 6 votes vote down vote up
@Override
public void write( final Map<String,String> settingContainer ,
    final String outputPath , final boolean overwrite ) throws IOException {
  File targetFile = new File( outputPath );
  if ( targetFile.exists() ) {
    if ( overwrite ) {
      if ( ! targetFile.delete() ) {
        throw new IOException( "Could not remove file. Target : " + outputPath );
      }
    } else {
      throw new IOException( "Output file is already exists. Target : " + outputPath );
    }
  }

  OutputStream out = new BufferedOutputStream( new FileOutputStream( outputPath ) );
  write( settingContainer , out );
}
 
Example #18
Source File: HprofParser.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse a java heap dump file
 *
 * @param dump Heap dump file to parse
 * @param debug Turn on/off debug file parsing
 * @param callStack Turn on/off tracking of object allocation call stack
 * @param calculateRefs Turn on/off tracking object allocation call stack
 * @throws Exception
 * @return File containing output from the parser
 */
public static File parse(File dump, boolean debug, boolean callStack, boolean calculateRefs) throws Exception {
    File out = new File("hprof." + System.currentTimeMillis() + ".out");
    if (out.exists()) {
        out.delete();
    }

    PrintStream psSystemOut = System.out;
    try (PrintStream psHprof = new PrintStream(new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath())))) {
        System.setOut(psHprof);

        int debugLevel = debug ? 2 : 0;
        try (Snapshot snapshot = Reader.readFile(dump.getAbsolutePath(), callStack, debugLevel)) {
            System.out.println("Snapshot read, resolving...");
            snapshot.resolve(calculateRefs);
            System.out.println("Snapshot resolved.");
        }
   } finally {
       System.setOut(psSystemOut);
   }

    return out;
}
 
Example #19
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Helper method to decrypt file
 * @param inputStream stream associated with encrypted file
 * @param outputStream stream associated with new output decrypted file
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
@RequiresApi(api = Build.VERSION_CODES.M)
private static void aesDecrypt(BufferedInputStream inputStream, BufferedOutputStream outputStream)
        throws NoSuchPaddingException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyStoreException, NoSuchProviderException,
        InvalidAlgorithmParameterException, IOException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance(ALGO_AES);
    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV.getBytes());

    cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), gcmParameterSpec);
    CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);

    byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
    int count;

    try {

        while ((count = cipherInputStream.read(buffer)) != -1) {

            outputStream.write(buffer, 0, count);
            ServiceWatcherUtil.POSITION+=count;
        }
    } finally {

        outputStream.flush();
        cipherInputStream.close();
        outputStream.close();
    }
}
 
Example #20
Source File: JDBCExporter.java    From CQL with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Writes the db export SQL script to a file.
 *
 * @param outFile the file to write to
 *
 * @throws IOException
 */
@Override
public void exportToFile(final File outFile) throws IOException {
	final PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFile)));

	mode = Mode.FILE;
	$ = dbd.getStatementSeparator();

	// Writes the initial comments, db name, and so on
	for (final String p : initialize()) {
		out.println(p);
	}

	// Now write the table (include foreign key references)
	for (final String t : createTables()) {
		out.println(t);
	}

	// Generate any necessary constraints
	for (final String c : createConstraints()) {
		out.println(c);
	}

	// Generate any additional extras needed by the db
	for (final String x : createExtras(true)) {
		out.println(x);
	}

	// Generare all views on this sketch
	for (final String v : createViews()) {
		out.println(v);
	}

	out.close();
}
 
Example #21
Source File: GifEncoder.java    From FlyCms with MIT License 5 votes vote down vote up
/**
 * 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 #22
Source File: CompressionUtil.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gzip compress a string
 * @param string the string to compress
 * @return the compressed data
 */
public static byte[] gzipCompress(String string) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
        GZIPOutputStream gz = new GZIPOutputStream(stream);
        BufferedOutputStream bufos = new BufferedOutputStream(gz, 5000000);
        bufos.write(string.getBytes());
        bufos.flush();
        bufos.close();
        return stream.toByteArray();
    }
    catch (IOException e) {
        return null;
    }
}
 
Example #23
Source File: FileHandler.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private void open(File fname, boolean append) throws IOException {
    int len = 0;
    if (append) {
        len = (int)fname.length();
    }
    FileOutputStream fout = new FileOutputStream(fname.toString(), append);
    BufferedOutputStream bout = new BufferedOutputStream(fout);
    meter = new MeteredStream(bout, len);
    setOutputStream(meter);
}
 
Example #24
Source File: OptimisticTypesPersistence.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Stores the map of optimistic types for a given function.
 * @param locationDescriptor the opaque persistence location descriptor, retrieved by calling
 * {@link #getLocationDescriptor(Source, int, Type[])}.
 * @param optimisticTypes the map of optimistic types.
 */
@SuppressWarnings("resource")
public static void store(final Object locationDescriptor, final Map<Integer, Type> optimisticTypes) {
    if(locationDescriptor == null || optimisticTypes.isEmpty()) {
        return;
    }
    final File file = ((LocationDescriptor)locationDescriptor).file;

    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            synchronized(getFileLock(file)) {
                if (!file.exists()) {
                    // If the file already exists, we aren't increasing the number of cached files, so
                    // don't schedule cleanup.
                    scheduleCleanup();
                }
                try (final FileOutputStream out = new FileOutputStream(file)) {
                    out.getChannel().lock(); // lock exclusive
                    final DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(out));
                    Type.writeTypeMap(optimisticTypes, dout);
                    dout.flush();
                } catch(final Exception e) {
                    reportError("write", file, e);
                }
            }
            return null;
        }
    });
}
 
Example #25
Source File: UnboundSSLUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void connect() throws IOException {
    System.out.println("Client: connect to server");
    try (BufferedInputStream bis = new BufferedInputStream(
                    socket.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(
                    socket.getOutputStream())) {

        for (byte[] bytes : arrays) {
            System.out.println("Client: send byte array: "
                    + Arrays.toString(bytes));

            bos.write(bytes);
            bos.flush();

            byte[] recieved = new byte[bytes.length];
            int read = bis.read(recieved, 0, bytes.length);
            if (read < 0) {
                throw new IOException("Client: couldn't read a response");
            }

            System.out.println("Client: recieved byte array: "
                    + Arrays.toString(recieved));

            if (!Arrays.equals(bytes, recieved)) {
                throw new IOException("Client: sent byte array "
                            + "is not equal with recieved byte array");
            }
        }
        socket.getSession().invalidate();
    } finally {
        if (!socket.isClosed()) {
            socket.close();
        }
    }
}
 
Example #26
Source File: ClsSet.java    From Box with Apache License 2.0 5 votes vote down vote up
void save(Path path) throws IOException {
	FileUtils.makeDirsForFile(path);
	String outputName = path.getFileName().toString();
	if (outputName.endsWith(CLST_EXTENSION)) {
		try (BufferedOutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(path))) {
			save(outputStream);
		}
	} else if (outputName.endsWith(".jar")) {
		Path temp = FileUtils.createTempFile(".zip");
		Files.copy(path, temp, StandardCopyOption.REPLACE_EXISTING);

		try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(path));
				ZipInputStream in = new ZipInputStream(Files.newInputStream(temp))) {
			String clst = CLST_PKG_PATH + '/' + CLST_FILENAME;
			out.putNextEntry(new ZipEntry(clst));
			save(out);
			ZipEntry entry = in.getNextEntry();
			while (entry != null) {
				if (!entry.getName().equals(clst)) {
					out.putNextEntry(new ZipEntry(entry.getName()));
					FileUtils.copyStream(in, out);
				}
				entry = in.getNextEntry();
			}
		}
	} else {
		throw new JadxRuntimeException("Unknown file format: " + outputName);
	}
}
 
Example #27
Source File: WaveFileWriter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
            int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip RIFF magic
            raf.skipBytes(4);
            raf.writeInt(big2little( riffLength ));
            // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
            raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
            raf.writeInt(big2little( dataLength ));
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example #28
Source File: AbstractTranslet.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/************************************************************************
 * Multiple output document extension.
 * See compiler/TransletOutput for actual implementation.
 ************************************************************************/

public SerializationHandler openOutputHandler(String filename, boolean append)
    throws TransletException
{
    try {
        final TransletOutputHandlerFactory factory
            = TransletOutputHandlerFactory.newInstance(_overrideDefaultParser);

        String dirStr = new File(filename).getParent();
        if ((null != dirStr) && (dirStr.length() > 0)) {
           File dir = new File(dirStr);
           dir.mkdirs();
        }

        factory.setEncoding(_encoding);
        factory.setOutputMethod(_method);
        factory.setOutputStream(new BufferedOutputStream(new FileOutputStream(filename, append)));
        factory.setOutputType(TransletOutputHandlerFactory.STREAM);

        final SerializationHandler handler
            = factory.getSerializationHandler();

        transferOutputSettings(handler);
        handler.startDocument();
        return handler;
    }
    catch (Exception e) {
        throw new TransletException(e);
    }
}
 
Example #29
Source File: TestFileUtils.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public static String createTempFile(long bytes) throws IOException {
	File f = File.createTempFile(FILE_PREFIX, FILE_SUFFIX);
	f.deleteOnExit();
	
	BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
	try { 
		for (; bytes > 0; bytes--) {
			out.write(0);
		}
	} finally {
		out.close();
	}
	return f.toURI().toString();
}
 
Example #30
Source File: BlockComplex.java    From L2jOrg with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final void saveBlock(BufferedOutputStream stream) throws IOException {
    // write block type
    stream.write(GeoStructure.TYPE_COMPLEX_L2D);

    // write block data
    stream.write(_buffer, 0, GeoStructure.BLOCK_CELLS * 3);
}