1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
public class Test {
public static void main(String args[]) {
Test test=new Test();
try {
// INPUT STREAM
String s="Gilbert Montagné";
InputStream in=new ByteArrayInputStream(s.getBytes());
// OUPUT STREAM
OutputStream out=System.out;
// try it
String res = test.tryOut(s.length(), false, in, out);
// Result
System.out.println();
System.out.println("res="+res);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String tryOut(int contentLength,boolean waitForDisconnect,InputStream in,OutputStream out) throws IOException {
// Input filter
Charset charsetIn=Charset.defaultCharset(); // Codifiaction choisie en input: "UTF-8",...
InputStreamReader inputStreamReader=new InputStreamReader(in,charsetIn);
// Output filter
Charset charsetOut=Charset.defaultCharset(); // Codifiaction choisie en output: "UTF-8",...
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(out,charsetOut);
//ByteArrayOutputStream baism = new ByteArrayOutputStream(contentLength);
//byte[] buf = new byte[4096];
CharBuffer buf= CharBuffer.allocate(contentLength);
//int byteCount=0;
//int bytesIn = 0;
int charCount=0;
int charIn = 0;
//while (((byteCount < contentLength) || (waitForDisconnect)) && ((bytesIn = in.read(buf)) >= 0)) {
while (((charCount < contentLength) || (waitForDisconnect)) && ((charIn = inputStreamReader.read(buf.array(),charCount,contentLength)) >= 0)) {
//out.write(buf, 0, bytesIn);
//baism.write(buf, 0, bytesIn);
outputStreamWriter.write(buf.array(), charCount, charIn);
//byteCount += bytesIn;
charCount += charIn;
}
outputStreamWriter.flush(); // Terminer l'écriture
//String metad = baism.toString();
String metad = buf.toString().substring(0,charCount);
return metad;
}
} |
Partager