I've some problems with InputStream after download an image. downloadImages method return an InputStream that i write in a file. But there is an exception in inputStreamToFile method: java.io.IOException: BufferedInputStream is closed. Here the codes:
Download
public static InputStream downloadImages(String imageUrl) {
HttpURLConnection httpConn = null;
String urlBase = imageUrl;
if(D) Log.d(TAG, "downloadImages(): url request: " + urlBase);
try {
URL url = new URL(urlBase);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(SystemConstants.TIMEOUT_CONNECTION);
httpConn.setReadTimeout(SystemConstants.SOCKET_CONNECTION);
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
return inputStream;
}
} catch (IOException e) {
Log.w(TAG, "downloadImages(): exception: " + e);
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(httpConn != null) httpConn.disconnect();
}
return null;
}
From IS to file
public static void inputStreamToFile(InputStream is) {
if(D) Log.d(TAG, "inputStreamToFile() called");
OutputStream outputStream = null;
try {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Utils.isExternalStorageRemovable() ?
Utils.getExternalCacheDir(App.getContext()).getPath() :
App.getContext().getCacheDir().getPath();
// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(cachePath + File.separator + "vr"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
if(D) Log.d(TAG, "read called");
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
if(D) Log.d(TAG, "inputStreamToFile(): outputStream is not null");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Put your logcat.Then only we can identify the errors,bugs,etc
Related
I want to download file(.docx,.pdf,image,or any type) from server.I am using spring-mvc REST API.By Using Resttemplate.exchange(...) i got Response from server in the form of stream but i am unable to parse it.So how should i do that and write into file?
File Return code (server) :
public ResponseEntity<?> downloadFile(..){
if (downloadFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(downloadFile);
return ResponseEntity.ok()
.contentLength(downloadFile.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(newInputStreamResource(fileInputStream));}
else {
return responseEntity.status(HttpStatus.NOT_FOUND)
.body(ErrorMsgWebapiUtil.AUTHORIZED_USER);
}
}
Response from Server:
<200 OK,PNG
������
IHDR����8����û������Þ¢ø������sBIT3���� ��IDATxíÝ?'T����pþÖé������T*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����óÿ��0\§ÁzõK��������IEND®B`
Code At my Android (client) :
try {
mRespEntity = mRestTemplate.exchange(strFinal, HttpMethod.POST, mRequestEntity, String.class);
mResponseCode = mRespEntity.getStatusCode().toString();
if (mResponseCode.equals("200")) {
String outdir = "sdcard/downloads/";
int length = Integer.parseInt(mRespEntity.getHeaders().getContentLength() + "");
inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody()); //Here it Throughs Exception:java.lang.String cannot be cast to java.io.InputStream
byte[] buffer = new byte[length];
int read = 0;
File dFile = new File(outdir, filename);
fos = new DataOutputStream(new FileOutputStream(dFile));
while ((read = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
}
} catch (Exception e) {
if (e != null) {
e.printStackTrace();
Log.e(TAG, "getFileFolderSyncData() Error:" + e.getMessage());
return false;
}
} finally {
// resetSSLFactory();
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
// outputStream.flush();
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At Line inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody()); here it through exception :"java.lang.String cannot be cast to java.io.InputStream"
Got solution...
public String FileDownload(...){
String url = ....;
String res = ...;
String outdir = ...;
File outputFile = new File(outdir, filename);
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("param1", value);//post parameters
String urlParameters = ...;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
in = new BufferedInputStream(con.getInputStream());
fout = new FileOutputStream(outputFile);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
res = "true";
} else {
res = con.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Exception in file Download:" + e.getMessage());
res = "false";
} finally {
try {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
res = "true";
} catch (IOException e) {
e.printStackTrace();
res = "false";
}
}
return res;
}
I need to download image from server and save it to folder, so I am using Retrofit 2.
Problem is that saved images is empty when I look for it in folder and I tried to debug and saw that Bitmap is null.
I do not get why, here is my code:
#GET("images/{userId}/{imageName}")
#Streaming
Call<ResponseBody> downloadImage(#Path("userId") String userId, #Path("imageName") String imageName);
Download image code:
private void downloadImage(final int position) {
String url = "htttp://myserver.com/";
retrofitImage = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
imageApi = retrofitImage.create(BlastApiService.class);
String userId = feedList.get(position).getUserId();
String fileName = feedList.get(position).getFile();
Call<ResponseBody> imageCall = imageApi.downloadImage(userId, fileName );
imageCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccess()){
String fileName = feedList.get(position).getFile();
InputStream is = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
saveImage1(bitmap, fileName);
} else{
try {
Log.d("TAG", "response error: "+response.errorBody().string().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "Image download error: " + t.getLocalizedMessage());
}
});
}
Here is method to save image.
private void saveImage1(Bitmap imageToSave, String fileName) {
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/FOLDER_NAME/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
counter++;
// if (counter < feedList.size()) {
//downloadImage(counter);
//} else {
setImage();
//}
} catch (Exception e) {
e.printStackTrace();
}
}
This worked for me:
public static boolean writeResponseBody(ResponseBody body, String path) {
try {
File file = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
//long fileSize = body.contentLength();
//long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(file);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
//fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
after call this method you can get image from path:
boolean result = writeResponseBody(body, path);
if(result) {
Bitmap bitmap = BitmapFactory.decodeFile(path)
}
private boolean writeResponseBodyToDisk(ResponseBody body, String name) {
try {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/MyApp";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File futureStudioIconFile = new File(path, name + ".pdf");//am saving pdf file
if (futureStudioIconFile.exists())
futureStudioIconFile.delete();
futureStudioIconFile.createNewFile();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
I want to retain some strings even when i clear my app data so i am using text files saved in sd card.
I am using sd card files to store myStrings and read them at run time. but each and every time readfile return null.
following is my code:
protected void writeToFile(String data, String fileName) {
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
if(dir.mkdir())
{
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
protected String readFromFile(String fileName, String defaultValue) {
String ret = "";
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
File file = new File(dir.getAbsolutePath() + "/"+fileName);
try {
//InputStream inputStream = openFileInput("/sdcard/"+fileName);
FileInputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
/*if((receiveString = bufferedReader.read) != null){
stringBuilder.append(receiveString);
}*/
String line="";
int c;
while ((c = bufferedReader.read()) != -1) {
line+=(char)c;
//counter++;
}
stringBuilder.append(line);
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
if (ret.equals("")) {
ret=defaultValue;
}
return ret;
}
try to add the "file:///" suffix before the Uri
I am downloading requested image from my server , this image is successfully displayed after downloading but when i try to store the same image on my SD card it returns null.
Here is my code for downloading image and saving it.I am getting null on a call to bitmap.compress()
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image.png";
File file = new File (myDir, fname);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
message_bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//write the bytes in file
FileOutputStream fo;
try {
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
message_bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}*/
}
static public Bitmap downloadBitmap(String url) {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + e.toString());
} finally {
if (client != null) {
}
}
return null;
}
I think you are pretty close there. How about something similar to the below which downloads and saves an image:
try {
img_value = new URL("your_url");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
mIcon1 = BitmapFactory.decodeStream(img_value.openConnection()
.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String filename = "your_filename.jpg";
File file = new File(dir, filename);
if (file.exists()) {
try{
file.delete();
}catch(Exception e){
//sdcard plugged in
}
}
try {
FileOutputStream out = new FileOutputStream(file);
mIcon1.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();//will occur if the phone is plugged in
}
I am trying to fetchg data from server like MP3 files, video files, etc. in my application. The application should show the list of video files received from the server.
How can I do this?
/** this function will download content from the internet */
static int writeData(String fileurl, boolean append, String path,
String filename, Activity mContext) throws CustomException {
URL myfileurl = null;
ByteArrayBuffer baf = null;
HttpURLConnection conn = null;
String mimeType="";
final int length;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) myfileurl
.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(100000);
length = conn.getContentLength();
mimeType=conn.getContentType().toString();
System.out.println("Extension..."+mimeType);
if(mimeType.equalsIgnoreCase("application/vnd.adobe.adept+xml") || mimeType.equalsIgnoreCase("text/html; charset=utf-8"))
return 0;
if (length > 0) {
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(1000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((byte) current);
mBufferError=false;
} catch (Exception e){
// TODO: handle exception
mBufferError=true;
e.printStackTrace();
throw new CustomException("### memory problem ", "Buffer Error");
}
}
}
} catch (IOException e) {
mBufferError=true;
e.printStackTrace();
}
try{
if(conn.getResponseCode()==200 && mBufferError==false)
{
path = path + "/" + filename;
boolean appendData = append;
FileOutputStream foutstream;
File file = new File(path);
boolean exist = false;
try {
if (appendData)
exist = file.exists();
else
exist = file.createNewFile();
} catch (IOException e) {
try {
return 1;
} catch (Exception err) {
Log.e("SAX", err.toString());
}
}
if (!appendData && !exist) {
} else if (appendData && !exist) {
} else {
try {
foutstream = new FileOutputStream(file, appendData);
foutstream.write(baf.toByteArray());
foutstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}catch (Exception e) {
// TODO: handle exception
throw new CustomException("### I/O problem ", "I/O Error");
}
return 1;
}
once download complete search the file with extension(.3gp) for video
hope it helps
Check this link,
https://stackoverflow.com/search?q=how+to+download+mp3+%2Cvideos+from+server+in+android
Try this code
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}
catch (Exception ex)
{
}
and after you want to use MediaPlayer
and create object of mediaplayer in your activity
and play.
mp.reset();
mp.start();