Java 类java.util.zip.GZIPOutputStream 实例源码
项目:CloudLand-Server
文件:IdBasedProtobufEncoder.java
@Override
protected void encode(ChannelHandlerContext ctx, MessageOrBuilder in, List<Object> out)
throws Exception {
Message msg = in instanceof Message ? (Message) in : ((Message.Builder) in).build();
int typeId = register.getTypeId(msg.getClass());
if (typeId == Integer.MIN_VALUE) {
throw new IllegalArgumentException("Unrecognisable message type, maybe not registered! ");
}
byte[] messageData = msg.toByteArray();
if (messageData.length <= 0) {
out.add(ByteBufAllocator.DEFAULT.heapBuffer().writeInt(typeId)
.writeInt(0));
return;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream def = new GZIPOutputStream(bos);
def.write(messageData);
def.flush();
def.close();
byte[] compressedData = bos.toByteArray();
out.add(ByteBufAllocator.DEFAULT.heapBuffer().writeInt(typeId).writeInt(compressedData.length)
.writeBytes(compressedData));
}
项目:letv
文件:ac.java
private static String c(String str) {
String str2 = null;
try {
byte[] bytes = str.getBytes(z[5]);
OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
OutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gZIPOutputStream.write(bytes);
gZIPOutputStream.close();
bytes = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
str2 = a.a(bytes);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
return str2;
}
项目:myfaces-trinidad
文件:StateUtils.java
public static final byte[] compress(byte[] bytes)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try
{
GZIPOutputStream gzip = new GZIPOutputStream(baos);
gzip.write(bytes, 0, bytes.length);
gzip.finish();
byte[] fewerBytes = baos.toByteArray();
gzip.close();
baos.close();
gzip = null;
baos = null;
return fewerBytes;
}
catch (IOException e)
{
throw new FacesException(e);
}
}
项目:tqdev-metrics
文件:PrometheusFileReporter.java
/**
* Compress.
*
* @param filename
* the filename
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void compress(String filename) throws IOException {
File current = new File(filename);
File dir = new File(metricPath);
FilenameFilter textFileFilter = (f, s) -> s.endsWith(".prom");
File[] directoryListing = dir.listFiles(textFileFilter);
if (directoryListing != null) {
for (File file : directoryListing) {
if (file.getCanonicalPath() != current.getCanonicalPath()) {
try (FileOutputStream fos = new FileOutputStream(file.getPath() + ".gz");
GZIPOutputStream gzos = new GZIPOutputStream(fos)) {
byte[] buffer = new byte[8192];
int length;
try (FileInputStream fis = new FileInputStream(file.getPath())) {
while ((length = fis.read(buffer)) > 0) {
gzos.write(buffer, 0, length);
}
}
}
file.delete();
}
}
} else {
throw new IOException("Directory not listable: " + metricPath);
}
}
项目:MARF-for-Android
文件:TransitionTable.java
/**
* Saves current state of the TT (itself).
*
* @return <code>true</code> if serialization was successful
*/
public boolean save() {
try {
// Save to file
FileOutputStream oFOS = new FileOutputStream(this.strTableFile);
// Compressed
GZIPOutputStream oGZOS = new GZIPOutputStream(oFOS);
// Save objects
ObjectOutputStream oOOS = new ObjectOutputStream(oGZOS);
oOOS.writeObject(this);
oOOS.flush();
oOOS.close();
return true;
} catch (IOException e) {
System.err.println("TransitionTable::save() - WARNING: " + e.getMessage());
e.printStackTrace(System.err);
return false;
}
}
项目:Quavo
文件:CompressionUtils.java
/**
* Compresses a GZIP file.
*
* @param bytes The uncompressed bytes.
* @return The compressed bytes.
* @throws IOException if an I/O error occurs.
*/
public static byte[] gzip(byte[] bytes) throws IOException {
/* create the streams */
InputStream is = new ByteArrayInputStream(bytes);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
OutputStream os = new GZIPOutputStream(bout);
try {
/* copy data between the streams */
byte[] buf = new byte[4096];
int len = 0;
while ((len = is.read(buf, 0, buf.length)) != -1) {
os.write(buf, 0, len);
}
} finally {
os.close();
}
/* return the compressed bytes */
return bout.toByteArray();
} finally {
is.close();
}
}
项目:OpenDiabetes
文件:ScriptWriterText.java
public ScriptWriterText(Database db, String file,
boolean includeCachedData, boolean compressed) {
super(db, file, includeCachedData, true, false);
if (compressed) {
isCompressed = true;
try {
fileStreamOut = new GZIPOutputStream(fileStreamOut);
} catch (IOException e) {
throw Error.error(e, ErrorCode.FILE_IO_ERROR,
ErrorCode.M_Message_Pair, new Object[] {
e.toString(), outFile
});
}
}
}
项目:JavaSDK
文件:PortfolioDataFile.java
/**
* Gzips the input then base-64 it.
*
* @param path the input data file, as an instance of {@link Path}
* @return the compressed output, as a String
*/
private static String gzipBase64(Path path) {
try {
long size = Files.size(path) / 4 + 1;
int initialSize = size > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) size;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(initialSize)) {
try (OutputStream baseos = Base64.getEncoder().wrap(baos)) {
try (GZIPOutputStream zos = new GZIPOutputStream(baseos)) {
Files.copy(path, zos);
}
}
return baos.toString("ISO-8859-1"); // base-64 bytes are ASCII, so this is optimal
}
} catch (IOException ex) {
throw new UncheckedIOException("Failed to gzip base-64 content", ex);
}
}
项目:jmeter-bzm-plugins
文件:LoadosophiaAPIClient.java
private File gzipFile(File src) throws IOException {
// Never try to make it stream-like on the fly, because content-length still required
// Create the GZIP output stream
String outFilename = src.getAbsolutePath() + ".gz";
notifier.notifyAbout("Gzipping " + src.getAbsolutePath());
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename), 1024 * 8, true);
// Open the input file
FileInputStream in = new FileInputStream(src);
// Transfer bytes from the input file to the GZIP output stream
byte[] buf = new byte[10240];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
// Complete the GZIP file
out.finish();
out.close();
src.delete();
return new File(outFilename);
}
项目:LearningOfThinkInJava
文件:GZIPcompress.java
public static void main(String[] args) throws IOException{
BufferedReader in=new BufferedReader(
new FileReader("./src/main/java/io/source/data1.txt")
);
BufferedOutputStream out=new BufferedOutputStream(new GZIPOutputStream(
new FileOutputStream("./src/main/java/io/source/data1.gz")
));
System.out.println("Writing file");
int c;
while ((c=in.read())!=-1){
out.write(c);
}
in.close();
out.close();
System.out.println("Reading file");
BufferedReader in2=new BufferedReader(
new InputStreamReader(new GZIPInputStream(
new FileInputStream("./src/main/java/io/source/data1.gz"))));
String s;
while ((s=in2.readLine())!=null){
System.out.println(s);
}
}
项目:Phoenix-for-VK
文件:BundleUtil.java
public static String serializeBundle(final Bundle bundle) {
String base64;
final Parcel parcel = Parcel.obtain();
try {
parcel.writeBundle(bundle);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final GZIPOutputStream zos = new GZIPOutputStream(new BufferedOutputStream(bos));
zos.write(parcel.marshall());
zos.close();
base64 = Base64.encodeToString(bos.toByteArray(), 0);
} catch (IOException e) {
e.printStackTrace();
base64 = null;
} finally {
parcel.recycle();
}
return base64;
}
项目:LT-ABSA
文件:ComputeIdf.java
/**
* Saves the IDF scores in a tab-separated format:<br>
* TOKEN   TOKEN_ID   IDF-SCORE   FREQUENCY
* @param idfFile path to the output file
*/
public void saveIdfScores(String idfFile) {
try {
Writer out;
if (idfFile.endsWith(".gz")) {
out = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(idfFile)), "UTF-8");
} else {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(idfFile), "UTF-8"));
}
for (String token : tokenIds.keySet()) {
int tokenId = tokenIds.get(token);
int frequency = documentFrequency.get(tokenId);
if (frequency >= minFrequency) {
double idfScore = Math.log(documentCount / frequency);
out.write(token + "\t" + tokenId + "\t" + idfScore + "\t" + frequency + "\n");
}
}
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
项目:aika
文件:Provider.java
public void save() {
if (n.modified) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (
GZIPOutputStream gzipos = new GZIPOutputStream(baos);
DataOutputStream dos = new DataOutputStream(gzipos);) {
n.write(dos);
} catch (IOException e) {
throw new RuntimeException(e);
}
model.suspensionHook.store(id, baos.toByteArray());
}
n.modified = false;
}
项目:minikube-build-tools-for-java
文件:TarStreamBuilderTest.java
@Test
public void testToBlob_withCompression() throws IOException {
Blob blob = testTarStreamBuilder.toBlob();
// Writes the BLOB and captures the output.
ByteArrayOutputStream tarByteOutputStream = new ByteArrayOutputStream();
OutputStream compressorStream = new GZIPOutputStream(tarByteOutputStream);
blob.writeTo(compressorStream);
// Rearrange the output into input for verification.
ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(tarByteOutputStream.toByteArray());
InputStream tarByteInputStream = new GZIPInputStream(byteArrayInputStream);
TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(tarByteInputStream);
verifyTarArchive(tarArchiveInputStream);
}
项目:boohee_v5.6
文件:CommonUtils.java
public static String textCompress(String str) {
try {
Object array = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(str.length()).array();
OutputStream byteArrayOutputStream = new ByteArrayOutputStream(str.length());
GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gZIPOutputStream.write(str.getBytes("UTF-8"));
gZIPOutputStream.close();
byteArrayOutputStream.close();
Object obj = new byte[(byteArrayOutputStream.toByteArray().length + 4)];
System.arraycopy(array, 0, obj, 0, 4);
System.arraycopy(byteArrayOutputStream.toByteArray(), 0, obj, 4, byteArrayOutputStream.toByteArray().length);
return Base64.encodeToString(obj, 8);
} catch (Exception e) {
return "";
}
}
项目:VASSAL-src
文件:TileUtils.java
/**
* Write a tile image to a stream.
*
* @param tile the image
* @param out the stream
*
* @throws ImageIOException if the write fails
*/
public static void write(BufferedImage tile, OutputStream out)
throws IOException {
ByteBuffer bb;
// write the header
bb = ByteBuffer.allocate(18);
bb.put("VASSAL".getBytes())
.putInt(tile.getWidth())
.putInt(tile.getHeight())
.putInt(tile.getType());
out.write(bb.array());
// write the tile data
final DataBufferInt db = (DataBufferInt) tile.getRaster().getDataBuffer();
final int[] data = db.getData();
bb = ByteBuffer.allocate(4*data.length);
bb.asIntBuffer().put(data);
final GZIPOutputStream zout = new GZIPOutputStream(out);
zout.write(bb.array());
zout.finish();
}
项目:RPGInventory
文件:BackpackSerializer.java
static void saveBackpack(Backpack backpack, Path file) throws IOException {
List<NbtCompound> nbtList = new ArrayList<>();
try (DataOutputStream dataOutput = new DataOutputStream(new GZIPOutputStream(Files.newOutputStream(file)))) {
ItemStack[] contents = backpack.getContents();
for (int i = 0; i < contents.length; i++) {
ItemStack item = contents[i];
nbtList.add(ItemUtils.itemStackToNBT(ItemUtils.isEmpty(item)
? new ItemStack(Material.AIR)
: item, i + ""));
}
NbtCompound backpackNbt = NbtFactory.ofCompound("Backpack");
backpackNbt.put(NbtFactory.ofCompound("contents", nbtList));
backpackNbt.put("type", backpack.getType().getId());
backpackNbt.put("last-use", backpack.getLastUse());
NbtBinarySerializer.DEFAULT.serialize(backpackNbt, dataOutput);
}
}
项目:PNet
文件:PacketCompressor.java
/**
* Compresses given Packet. Note that this can increase the total size when used incorrectly
* @param packet Packet to compress
* @return Compressed Packet
* @throws IOException when unable to compress
*/
public static Packet compress(final Packet packet) throws IOException
{
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)
{
{
def.setLevel(Deflater.BEST_COMPRESSION);
}
};
// Deflate all data
gzipOutputStream.write(packet.getData());
gzipOutputStream.close();
return new Packet(
packet.getPacketType(),
packet.getPacketID(),
byteArrayOutputStream.toByteArray()
);
}
项目:financisto1-holo
文件:Export.java
public String export() throws Exception {
File path = getBackupFolder(context);
String fileName = generateFilename();
File file = new File(path, fileName);
FileOutputStream outputStream = new FileOutputStream(file);
try {
if (useGzip) {
export(new GZIPOutputStream(outputStream));
} else {
export(outputStream);
}
} finally {
outputStream.flush();
outputStream.close();
}
return fileName;
}
项目:neoscada
文件:DebianPackageWriter.java
public DebianPackageWriter ( final OutputStream stream, final GenericControlFile packageControlFile, final TimestampProvider timestampProvider ) throws IOException
{
this.packageControlFile = packageControlFile;
this.timestampProvider = timestampProvider;
if ( getTimestampProvider () == null )
{
throw new IllegalArgumentException ( "'timestampProvider' must not be null" );
}
BinaryPackageControlFile.validate ( packageControlFile );
this.ar = new ArArchiveOutputStream ( stream );
this.ar.putArchiveEntry ( new ArArchiveEntry ( "debian-binary", this.binaryHeader.length, 0, 0, AR_ARCHIVE_DEFAULT_MODE, getTimestampProvider ().getModTime () / 1000 ) );
this.ar.write ( this.binaryHeader );
this.ar.closeArchiveEntry ();
this.dataTemp = File.createTempFile ( "data", null );
this.dataStream = new TarArchiveOutputStream ( new GZIPOutputStream ( new FileOutputStream ( this.dataTemp ) ) );
this.dataStream.setLongFileMode ( TarArchiveOutputStream.LONGFILE_GNU );
}
项目:neoscada
文件:DebianPackageWriter.java
private void buildAndAddControlFile () throws IOException, FileNotFoundException
{
final File controlFile = File.createTempFile ( "control", null );
try
{
try ( GZIPOutputStream gout = new GZIPOutputStream ( new FileOutputStream ( controlFile ) );
TarArchiveOutputStream tout = new TarArchiveOutputStream ( gout ) )
{
tout.setLongFileMode ( TarArchiveOutputStream.LONGFILE_GNU );
addControlContent ( tout, "control", createControlContent (), -1 );
addControlContent ( tout, "md5sums", createChecksumContent (), -1 );
addControlContent ( tout, "conffiles", createConfFilesContent (), -1 );
addControlContent ( tout, "preinst", this.preinstScript, EntryInformation.DEFAULT_FILE_EXEC.getMode () );
addControlContent ( tout, "prerm", this.prermScript, EntryInformation.DEFAULT_FILE_EXEC.getMode () );
addControlContent ( tout, "postinst", this.postinstScript, EntryInformation.DEFAULT_FILE_EXEC.getMode () );
addControlContent ( tout, "postrm", this.postrmScript, EntryInformation.DEFAULT_FILE_EXEC.getMode () );
}
addArFile ( controlFile, "control.tar.gz" );
}
finally
{
controlFile.delete ();
}
}
项目:hadoop
文件:WritableUtils.java
public static int writeCompressedByteArray(DataOutput out,
byte[] bytes) throws IOException {
if (bytes != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzout = new GZIPOutputStream(bos);
try {
gzout.write(bytes, 0, bytes.length);
gzout.close();
gzout = null;
} finally {
IOUtils.closeStream(gzout);
}
byte[] buffer = bos.toByteArray();
int len = buffer.length;
out.writeInt(len);
out.write(buffer, 0, len);
/* debug only! Once we have confidence, can lose this. */
return ((bytes.length != 0) ? (100*buffer.length)/bytes.length : 0);
} else {
out.writeInt(-1);
return -1;
}
}
项目:euphrates
文件:S3Writer.java
RowEnqueuer(S3Writer writer, Config.Table table, ReusableCountLatch finished) {
this.writer = writer;
this.table = table;
this.finished = finished;
try {
String id = UUID.randomUUID().toString();
file = new File("/tmp/" + id + ".json.gz");
mapper = new ObjectMapper();
fileWriter =
new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file)), "UTF-8");
file.deleteOnExit();
} catch (Exception e) {
App.fatal(e);
}
}
项目:myfaces-trinidad
文件:Base64OutputStreamTest.java
/**
* Testing writing binary data whose byte values range from -128 to 128.
* We create such data by GZIP-ing the string before writing out to the Base64OutputStream.
*
*/
public void testWriteBinaryData() throws IOException
{
String str = "Base64 Encoding is a popular way to convert the 8bit and the binary to the 7bit for network trans using Socket, and a security method to handle text or file, often used in Authentical Login and Mail Attachment, also stored in text file or database. Most SMTP server will handle the login UserName and Password in this way.";
String str_encoded = "H4sIAAAAAAAAAD2QQW7DMAwEv7IPCHIK2l4ToLe6CJD2AbREx0JkMpDouvl9KQXokVxylssTVX454F2CxiRXpArCXe9rpoKNHjBFUPnhYrCZ8TYmA0nsxZiESh9p1WuTJi0Qtk3LDVZIKtbauBcNN7ZdXyVUDmtJ9sDCNmtshNmVzDD+NThjSpl30MlYnMARSXBc3UYsBcr40Kt3Gm2glHE0ozAvrrpFropqWp5bndhwDRvJaPTIewxaDZfh6+zHFI+HLeX8f4XHyd3h29VPWrhbnalWT/bEzv4qf9D+DzA2UNlCAQAA";
byte[] bytes = str.getBytes();
StringWriter strwriter = new StringWriter();
BufferedWriter buffwriter = new BufferedWriter(strwriter);
Base64OutputStream b64_out = new Base64OutputStream(buffwriter);
GZIPOutputStream zip = new GZIPOutputStream(b64_out);
zip.write(bytes, 0, bytes.length);
zip.finish();
buffwriter.flush();
b64_out.close();
assertEquals(str_encoded, strwriter.toString());
}
项目:monarch
文件:OSProcess.java
/** dumps this vm's stacks and returns gzipped result */
public static byte[] zipStacks() throws IOException {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] threadIds = bean.getAllThreadIds();
ThreadInfo[] infos = bean.getThreadInfo(threadIds, true, true);
long thisThread = Thread.currentThread().getId();
ByteArrayOutputStream baos = new ByteArrayOutputStream(10000);
GZIPOutputStream zipOut = new GZIPOutputStream(baos, 10000);
PrintWriter pw = new PrintWriter(zipOut, true);
for (int i = 0; i < infos.length; i++) {
if (i != thisThread && infos[i] != null) {
formatThreadInfo(infos[i], pw);
}
}
pw.flush();
zipOut.close();
byte[] result = baos.toByteArray();
return result;
}
项目:spark_deep
文件:WritableUtils.java
public static int writeCompressedByteArray(DataOutput out,
byte[] bytes) throws IOException {
if (bytes != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzout = new GZIPOutputStream(bos);
gzout.write(bytes, 0, bytes.length);
gzout.close();
byte[] buffer = bos.toByteArray();
int len = buffer.length;
out.writeInt(len);
out.write(buffer, 0, len);
/* debug only! Once we have confidence, can lose this. */
return ((bytes.length != 0) ? (100*buffer.length)/bytes.length : 0);
} else {
out.writeInt(-1);
return -1;
}
}
项目:monarch
文件:CacheServerHelper.java
public static byte[] zip(Object obj) throws IOException {
// logger.info("CacheServerHelper: Zipping object to blob: " + obj);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gz = new GZIPOutputStream(baos);
ObjectOutputStream oos = new ObjectOutputStream(gz);
oos.writeObject(obj);
oos.flush();
oos.close();
byte[] blob = baos.toByteArray();
// logger.info("CacheServerHelper: Zipped object to blob: " + blob);
return blob;
}
项目:multiple-dimension-spread
文件:GzipCompressor.java
@Override
public void compress( final byte[] data , final int start , final int length , final OutputStream out ) throws IOException{
GZIPOutputStream gzipOut = new GZIPOutputStream( out );
gzipOut.write( data , start , length );
gzipOut.flush();
gzipOut.finish();
}
项目:recruitervision
文件:Transducer.java
public void actionPerformed(java.awt.event.ActionEvent evt) {
Runnable runnable = new Runnable() {
public void run() {
JFileChooser fileChooser = MainFrame.getFileChooser();
fileChooser.setFileFilter(fileChooser.getAcceptAllFileFilter());
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(false);
if(fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
ObjectOutputStream out = null;
try {
MainFrame.lockGUI("Saving binary JAPE Plus Transducer...");
out = new ObjectOutputStream(
new GZIPOutputStream(
new BufferedOutputStream(
new FileOutputStream(file))));
out.writeObject(singlePhaseTransducersData);
} catch(IOException ioe) {
JOptionPane.showMessageDialog(MainFrame.getInstance(),
"Error!\n" + ioe.toString(), "GATE",
JOptionPane.ERROR_MESSAGE);
ioe.printStackTrace(Err.getPrintWriter());
} finally {
if(out != null) {
try {
out.flush();
out.close();
} catch(IOException e) {
log.error("Exception while closing output stream.", e);
}
}
MainFrame.unlockGUI();
}
}
}
};
Thread thread = new Thread(runnable, "JAPE Plus binary save thread");
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
项目:Reer
文件:GZipTaskOutputPacker.java
@Override
public void pack(TaskOutputsInternal taskOutputs, OutputStream output, TaskOutputOriginWriter writeOrigin) {
GZIPOutputStream gzipOutput = createGzipOutputStream(output);
try {
delegate.pack(taskOutputs, gzipOutput, writeOrigin);
} finally {
IOUtils.closeQuietly(gzipOutput);
}
}
项目:Reer
文件:GZipTaskOutputPacker.java
private GZIPOutputStream createGzipOutputStream(OutputStream output) {
try {
return new GZIPOutputStream(output);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
项目:Vanilla-Injection
文件:Structure.java
/**
* Write the <a href="https://minecraft-de.gamepedia.com/NBT-Format">NBT</a> obtained by calling
* {@link #toNbt()} to the specified {@link File}.
*
* @param file the {@link File} to write to
* @throws IOException if an I/O error has occurred
*/
public void writeTo(File file) throws IOException {
Files.createParentDirs(file);
TagCompound nbt = toNbt();
try (NbtOutputStream out =
new NbtOutputStream(new GZIPOutputStream(new FileOutputStream(file)))) {
out.write(nbt);
}
}
项目:Nukkit-Java9
文件:TimingsExport.java
@Override
public void run() {
this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadStart"));
this.out.add("data", JsonUtil.mapToArray(this.history, TimingsHistory::export));
String response = null;
try {
HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
con.setDoOutput(true);
con.setRequestProperty("User-Agent", "Nukkit/" + Server.getInstance().getName() + "/" + InetAddress.getLocalHost().getHostName());
con.setRequestMethod("POST");
con.setInstanceFollowRedirects(false);
OutputStream request = new GZIPOutputStream(con.getOutputStream()) {
{
this.def.setLevel(7);
}
};
request.write(new Gson().toJson(this.out).getBytes("UTF-8"));
request.close();
response = getResponse(con);
if (con.getResponseCode() != 302) {
this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadError", new String[]{String.valueOf(con.getResponseCode()), con.getResponseMessage()}));
if (response != null) {
Server.getInstance().getLogger().alert(response);
}
return;
}
String location = con.getHeaderField("Location");
this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.timingsLocation", location));
if (!(this.sender instanceof ConsoleCommandSender)) {
Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location));
}
if (response != null && !response.isEmpty()) {
Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsResponse", response));
}
File timingFolder = new File(Server.getInstance().getDataPath() + File.separator + "timings");
timingFolder.mkdirs();
String fileName = timingFolder + File.separator + new SimpleDateFormat("'timings-'yyyy-MM-dd-hh-mm'.txt'").format(new Date());
FileWriter writer = new FileWriter(fileName);
writer.write(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location) + "\n\n");
writer.write(new GsonBuilder().setPrettyPrinting().create().toJson(this.out));
writer.close();
Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsWrite", fileName));
} catch (IOException exception) {
this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError"));
if (response != null) {
Server.getInstance().getLogger().alert(response);
}
Server.getInstance().getLogger().logException(exception);
}
}
项目:hadoop
文件:TestCombineFileInputFormat.java
static FileStatus writeGzipFile(Configuration conf, Path name,
short replication, int numBlocks)
throws IOException, TimeoutException, InterruptedException {
FileSystem fileSys = FileSystem.get(conf);
GZIPOutputStream out = new GZIPOutputStream(fileSys.create(name, true, conf
.getInt("io.file.buffer.size", 4096), replication, (long) BLOCKSIZE));
writeDataAndSetReplication(fileSys, name, out, replication, numBlocks);
return fileSys.getFileStatus(name);
}
项目:VBrowser-Android
文件:NanoHTTPD.java
private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {
if (encodeAsGzip) {
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
sendBody(gzipOutputStream, -1);
gzipOutputStream.finish();
} else {
sendBody(outputStream, pending);
}
}
项目:incubator-netbeans
文件:Installer.java
private static void uploadGZFile(PrintStream os, File f) throws IOException {
GZIPOutputStream gzip = new GZIPOutputStream(os);
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(f))) {
byte[] buffer = new byte[4096];
int readLength = is.read(buffer);
while (readLength != -1){
gzip.write(buffer, 0, readLength);
readLength = is.read(buffer);
}
} finally {
gzip.finish();
}
}
项目:s-store
文件:Encoder.java
public static byte[] compressAndBase64EncodeToBytes(String string) {
try {
byte[] inBytes = string.getBytes("UTF-8");
ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(string.length() * 0.7));
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write(inBytes);
gzos.close();
byte[] outBytes = baos.toByteArray();
return Base64.encodeBytesToBytes(outBytes);
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
项目:mynlp
文件:GzipUtils.java
public static byte[] gZip(byte[] data) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data);
gzip.finish();
gzip.close();
b = bos.toByteArray();
bos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return b;
}
项目:powsybl-core
文件:NetworkXml.java
public static byte[] gzip(Network network) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (GZIPOutputStream gzos = new GZIPOutputStream(bos)) {
write(network, gzos);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bos.toByteArray();
}
项目:Melophile
文件:BundleUtils.java
public static byte[] compress(String data){
if(data==null) return null;
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
try {
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}catch (IOException ex){
ex.printStackTrace();
}
return null;
}