I want to read from a stream. In entity, i don't set content length and for this, i can't create a buffer with fixed and correct size. I create a buffer with 16384 length but my data is more and a parts of my data lost! I want to read from stream and write to char array and i don't want to read with readLine. How can i write this code? Please explain with a part of code.
Thanks
char[] buffer;
if (contentLength == -1)
buffer = new char[16038];
else
buffer = new char[contentLength];
InputStream stream = responseEntity.getContent();
//String resultS=convertStreamToString(stream);
InputStreamReader streamReader = new InputStreamReader(stream,"UTF-8");
int hasRead = 0;
int readSize = 0;
int bufferLength = buffer.length;
//List<Byte> listChar=new ArrayList<Byte>();
while (hasRead < bufferLength) {
readSize = streamReader.read(buffer, hasRead, bufferLength
- hasRead);
if (readSize == -1)
break;
hasRead += readSize;
}
Replace the code you posted with this:
InputStream stream = responseEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
char buffer[] = sb.toString().toCharArray();
Related
I am trying to compress a large string object. This is what i tried, but i am unable to understand how to get compressed data, and how to define different type of compression tools.
This is what i got from Android docs.
byte[] input = jsonArray.getBytes("UTF-8");
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
compresser.end();
compresser.deflate(output) gives me a int number, 100
but i am unable to understand which method will give me the compressed output that i can send to service.
The algorithm that I compress my data with is Huffman. You can find it by a simple search. But in your case maybe it helps you:
public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
And to decompress it you can use:
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}
The documentation for Deflator shows that the output gets put into the buffer output
try {
// Encode a String into bytes
String inputString = "blahblahblah";
byte[] input = inputString.getBytes("UTF-8");
// Compress the bytes
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
compresser.end();
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0, compressedDataLength);
byte[] result = new byte[100];
int resultLength = decompresser.inflate(result);
decompresser.end();
// Decode the bytes into a String
String outputString = new String(result, 0, resultLength, "UTF-8");
} catch(java.io.UnsupportedEncodingException ex) {
// handle
} catch (java.util.zip.DataFormatException ex) {
// handle
}
all code you need to ENCODE, COMPRESS , DECOMPRESS , DECODE
I want to use my user.json which is in my raw folder to get a new File :
// read from file, convert it to user class
User user = mapper.readValue(new File(**R.raw.user**), User.class);
I found that InputStream can do it :
InputStream ins = res.openRawResource(
getResources().getIdentifier("raw/user",
"raw", getPackageName()));
Is there a better way to do it, directly with my json file ID ?
InputStream is = getResources().openRawResource(R.raw.json_file);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String jsonString = writer.toString();
ObjectMapper.readValue also take InputStream as source . Get InputStream using openRawResource method from json file and pass it to readValue :
InputStream in = getResources().openRawResource(R.raw.user);
User user = mapper.readValue(in, User.class);
Kotlin way :
val raw = resources.openRawResource(R.raw.posts)
val writer: Writer = StringWriter()
val buffer = CharArray(1024)
raw.use { rawData ->
val reader: Reader = BufferedReader(InputStreamReader(rawData, "UTF-8"))
var n: Int
while (reader.read(buffer).also { n = it } != -1) {
writer.write(buffer, 0, n)
}
}
val jsonString = writer.toString()
I'm getting data from an api and I want to write/save some file with that data. This is my code
try
{
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/incubate_files");
if (!myDir.exists()) myDir.mkdirs();
File file = new File(Environment.getExternalStorageDirectory().getPath()+File.separator+"/incubate_files/", "messageId_"+messageId+"."+ext);
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = content.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
output.close();
output.flush();
content.close();
}
catch (Exception e)
{
e.printStackTrace();
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
There is no exception, only a empty file
Thanks!
UPDATE
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
Log.d(app.TAG,"Cadena: "+builder.toString());
InputStream is = new ByteArrayInputStream(builder.toString().getBytes());
I change my InputStream white the content of the api. The api returns a lot of characters. The image actually exists in the server and I can see it.
Now the file is with some bytes but I cant see in my phone
The api reponse is in binary
You need to make use of getInputStream method from connection object and save the data into a File. For example:
InputStream input = connection.getInputStream();
File file = new File("download_directory_path", "file_name");
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = input.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
and then finally close() your output and input streams.
Once, writing is complete, the file points to the downloaded file.
How can I load a local html file(from assets folder) to a String?
I tried this code but the result is only "?????...".
InputStream is = getAssets().open("aaa.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
System.out.println(str);
thanks for any help!
You are not reading the whole file. Try this:
StringBuilder builder = new StringBuilder();
byte[] buffer = new byte[1024];
while(is.read(buffer) != -1) {
builder.append(new String(buffer));
}
is.close();
String str = builder.toString();
try this......
File file = new File("file:///android_asset/yuor_file.html");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String linewise = br.readLine();
while(linewise != null) {
sb.append(linewise );
sb.append("\n");
linewise = br.readLine();
}
//now data in sb
I have cheerapp.wav or cheerapp.mp3 or some other format.
InputStream in = context.getResources().openRawResource(R.raw.cheerapp);
BufferedInputStream bis = new BufferedInputStream(in, 8000);
// Create a DataInputStream to read the audio data from the saved file
DataInputStream dis = new DataInputStream(bis);
byte[] music = null;
music = new byte[??];
int i = 0; // Read the file into the "music" array
while (dis.available() > 0) {
// dis.read(music[i]); // This assignment does not reverse the order
music[i]=dis.readByte();
i++;
}
dis.close();
For the music byte array which takes the data from the DataInputStream. I don't know what the length of that to allocate.
This is raw file from resource not a file therefore I wouldn't know the size of that thing.
You do have byte array length as you can see:
InputStream inStream = context.getResources().openRawResource(R.raw.cheerapp);
byte[] music = new byte[inStream.available()];
And then you can read whole Stream into byte array easily.
Of course I would recommend that you do check when it comes to the size and use ByteArrayOutputStream with smaller byte[] buffer if needed:
public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling function
}
If you'll be doing lots of IO operations I recommend that you make use of org.apache.commons.io.IOUtils. That way you won't need to worry too much about quality of your IO implementation and once you import JAR into your project you would just do:
byte[] payload = IOUtils.toByteArray(context.getResources().openRawResource(R.raw.cheerapp));
Hope it will help.
Create an sdcard path:
String outputFile =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
Convert as a file and have to call the byte array method:
byte[] soundBytes;
try {
InputStream inputStream =
getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));
soundBytes = new byte[inputStream.available()];
soundBytes = toByteArray(inputStream);
Toast.makeText(this, "Recordin Finished"+ " " + soundBytes, Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
method:
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
In Kotlin use
InputStream.readBytes()