Skip to content

Instantly share code, notes, and snippets.

@Viacheslav77
Created November 23, 2016 22:36
Show Gist options
  • Save Viacheslav77/7851388516da42f9d57b62b1cebd1c57 to your computer and use it in GitHub Desktop.
Save Viacheslav77/7851388516da42f9d57b62b1cebd1c57 to your computer and use it in GitHub Desktop.
Написать chunk-encoder и chunk-decoder. Использовать InputStream/OutputStream как основу. Усложнил задачу, используя случайную длину блока для дробления на части контента.
package com.company.ChunkerDeChunker;
import java.io.*;
import java.util.Random;
public class Chunker {
private int chunkSize = 20;
private static ByteArrayOutputStream res;
public void process(String content) {
System.out.println("Исходный текст ... " + content +"\n");
byte [] data = content.getBytes();
try (ByteArrayOutputStream os = new ByteArrayOutputStream()){
int offset = 0;
Random r = new Random();
while (chunkSize>0) {
chunkSize = r.nextInt(20);
if ((data.length - offset) > chunkSize){
writeDate (data, offset, os);
offset += chunkSize;
}
else {
chunkSize = data.length - offset;
writeDate (data, offset, os);
chunkSize = 0;
}
}
System.out.println( "Chunker ...\n" + os);
res = os;
} catch (IOException ex) {
System.out.println( "Chunker process fails");
}
}
private void writeDate (byte[] data, int offset, ByteArrayOutputStream os) throws IOException{
String head = Integer.toHexString(chunkSize) + "\r\n";
os.write(head.getBytes());
os.write(data, offset, chunkSize);
os.write("\r\n".getBytes());
}
public byte[] getOs(){
return res.toByteArray();
}
}
Исходный текст ... 11111111112222222222333333333344444444445555555555
Chunker ...
12
111111111122222222
7
2233333
6
333334
2
44
a
4444444555
2
55
5
55555
DeChunker ... 11111111112222222222333333333344444444445555555555
package com.company.ChunkerDeChunker;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
class DeChunker{
public void process(byte[] data) {
try (ByteArrayInputStream bas = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bas)) {
String x;
int count =0;
String res = "";
while((x = dis.readLine())!= null){
if (count==1){
res += x;
count=0;
}
else
count=1;
}
System.out.println("DeChunker ... " + res);
} catch (IOException ex) {
}
}
}
package com.company.ChunkerDeChunker;
// Написать chunk-encoder и chunk-decoder. Использовать
// InputStream/OutputStream как основу.
public class Main {
public static void main(String[] args) {
String content = "11111111112222222222333333333344444444445555555555";
Chunker chunk = new Chunker();
chunk.process(content);
DeChunker deChunks = new DeChunker();
deChunks.process(chunk.getOs());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment