Saving image by url to internal storage - java

Please, need help. I'm having this error java.io.FileNotFoundException: http://news.yandex.ru/quotes/1507.png (can be seen by browser) while saving it to my internal storage.
this is my method:
void downloadGraph(String link){
try {
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File dbDirectory = new File(mctx.getFilesDir().getAbsolutePath()+ File.separator+"yqimages/");
if(!dbDirectory.exists())dbDirectory.mkdir();
String fname=link.substring(link.lastIndexOf("/")+1,link.length());
File file = new File(dbDirectory, fname);
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
Can you write a method to download\save this specific image (shown above)? Any help is appreciated!
Get it!! the problem is not in the code, it's in the image https://news.yandex.ru/quotes/1507.png. For some reason this picture can't be saved while the other ones do. Has it something to do with "httpS://"?

here explain all about download and save images in android.
And don't forget to add permission in Manifest for read and write external memory file.

// ist put the permission in Manifest.xml hte permission are below
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
private void saveimage() {
bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
String time = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(System.currentTimeMillis());
File path = Environment.getExternalStorageDirectory();
File dir = new File(path+"/Gallery");
dir.mkdir();
String imagename = time+".PNG";
File file = new File(dir,imagename);
OutputStream out;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,out);
out.flush();
out.close();
Toast.makeText(Show_Online.this, "Image Save To Gallery",
Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(Show_Online.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}

Related

Can't create folder in internal storage

Well, I'm trying to create a folder in my internal storage.
I have watched some tutorial but it's not working at all.
private void createDir() {
String folderName;
folderName = "myFolder";
File file = new File(Environment.getExternalStorageDirectory(), folderName);
if(!file.exists()){
file.mkdir();
Toast.makeText(getContext(),"Successful", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(),"Folder already exist", Toast.LENGTH_SHORT).show();
}
}
This is my method to create the new directory.
When I launch it, I receive the Toast "Successful" all the time.
But the directory is never created.
Just below the code for the permissions.
if(!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.SEND_SMS)){
String[] permissions = {Manifest.permission.WRITE_CALL_LOG,Manifest.permission.SEND_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_SMS};
ActivityCompat.requestPermissions(getActivity(),permissions,1);
}else{
lay_dataset1=view.findViewById(R.id.lay_dataset1);
messagePerm();
}
Here my manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Can someone explain what is happening :)
EDIT :
private void copyAssets() {
AssetManager assetManager = getContext().getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getContext().getExternalFilesDir(null).getParent().replace("files","myfolder"), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I tried this, I was able to move files that were in my "asset" folder at the same level as the "files" directory so why shouldn't I have the right to create a folder in this same location ?
At the first time you run your application, the app external storage directory
at Android/data/<package.name>/files is not created until you call this method getExternalFilesDir(null) Twice.
So try this code..
//Essential for creating the external storage directory for the first launch
getExternalFilesDir(null);
/*
output->> /storage/emulated/0/Android/data/<package.name>/files
*/
Log.i("HINT",getExternalFilesDir("").getAbsolutePath());
//Or create your custom folder
File outFile = new File(getExternalFilesDir(null).getParent(),"myfolder");
//make it as it is not exists
outFile.mkdirs();
/*
output->> /storage/emulated/0/Android/data/<package.name>/myfolder
*/
Log.i("HINT",outFile.getAbsolutePath());

How to create File object from assets folder?

I am trying to read a pdf file from my assets folder but I do not know how to get the path of pdf file.
I right click on pdf file and select "copy Path" and paste it
Here is the another screen shot of my code:
Here is my code:
File file = new File("/Users/zulqarnainmustafa/Desktop/ReadPdfFile/app/src/main/assets/Introduction.pdf");
if (file.exists()){
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
this.startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application available to view PDF", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this, "File path not found", Toast.LENGTH_LONG).show();
}
I always get file not found, Help me to create File object or let me know how I can get the exact path for a file I also tried with file:///android_asset/Introduction.pdf but no success. I also tried with Image.png but never gets file.exists() success. I am using Mac version of Android studio. Thanks
get input stream from asset and convert it to a file object.
File f = new File(getCacheDir()+"/Introduction.pdf");
if (!f.exists())
try {
InputStream is = getAssets().open("Introduction.pdf");
byte[] buffer = new byte[1024];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
Short converter (storing asset as cache file) in Kotlin:
fun fileFromAsset(name: String) : File =
File("$cacheDir/$name").apply { writeBytes(assets.open(name).readBytes()) }
cacheDir is just shorthand for this.getCacheDir() and should be predefined for you.
Can you try this code
AssetManager am = getAssets();
InputStream inputStream = am.open("Indroduction.pdf");
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("new FilePath");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
Then try with
File file = new File("new file path");
if (file.exists())

I want to download a file programically in android but when run,it closed?

I think my connection failed but I cant Repair code.
URL url = new URL( imageURL);
File file = new File(fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
when debug it crashed in this part of code.
I use
<uses-permission android:name="android.permission.INTERNET"/>
and
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Write below code into your MainActivity after setContentView(R.layout.activity_main)
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Above android 3.0 you need to do all your networking in a seperate thread.
So if you try that code in the main thred it will throw a NetworkOnMainThread exception.
try this to verify it:
try{
URL url = new URL( imageURL);
File file = new File(fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
}
catch (android.os.NetworkOnMainThreadException ex){
// Skipp.
}
If your app doesn't crashes this way then you need to use an AssyncTask for the networking.
Here is a good examplehow to .
And don't forget to check your filepath as well like #LucianNovac suggests.
Try to initialize the file like this:
File extStore = Environment.getExternalStorageDirectory();
File file = new File(extStore, fileName);
and don't forget to put in your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Also to avoid Network exception put this into an asynk
class DownloadMyFIle extends AsyncTask<String, Void, DownloadProcess> {
private Exception exception;
protected DownloadProcess doInBackground(String... urls) {
try {
File extStore = Environment.getExternalStorageDirectory();
File file = new File(extStore, fileName);
....
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(DownloadProcess process) {
// TODO: check this.exception
}
}

thumbnail video from url using image?

I already success display thumbnail video from URL on my android app when internet connection is connected, but when internet connection is off the thumbnail doesn't display.
here is my code.
Bitmap bmThumbnail;
bmThumbnail = ThumbnailUtils.createVideoThumbnail("http://somedomain.com/video/myvideo.mp4", Thumbnails.MICRO_KIND );
imgPhoto.setImageBitmap(bmThumbnail);
i want the thumbnail still display although connection is off,there is away to achieve like save the cache on sdcard first, like image cache does? or any other solution to show thumbnail video when internet connection is off?
thanks,
public static String getBitmapFromURL(final Activity activity, String link,
String filename) throws FileNotFoundException,
MalformedURLException, IOException {
/*--- this method downloads an Image from the given URL,
* then decodes and returns a Bitmap object
---*/
File file = null;
file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ CommonVariable.KCS_IMAGE_FOLDER_NAME_PHONE_MEMORY);
// have the object build the directory structure, if needed.
if (!file.exists()) {
file.mkdirs();
}
// create a File object for the output file
File outputFile = new File(file, filename);
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedOutputStream out = new BufferedOutputStream(fos, 1024);
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
out = new BufferedOutputStream(fos, 1024);
int b;
while ((b = input.read()) != -1) {
out.write(b);
}
out.close();
connection.disconnect();
return outputFile.getAbsolutePath();
}
use this function,it will return string of sdcard path.and use this path u can set bitmap image using below function:
public static void setImagesNew(ImageView img, String pathName,
Activity activity) {
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(pathName, Thumbnails.MICRO_KIND );
img.setImageBitmap(bmThumbnail);
bmp = null;
System.gc();
Runtime.getRuntime().gc();
}
i hope this is useful to you...............

Trouble with uploading a file from an applet to servlet

I am working on an applet that records voice and uploads to a servlet.
Here is the code of the upload thread in the applet
class uploadThread extends Thread {
#Override
public void run() {
try {
//Preparing the file to send
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File file = File.createTempFile("uploded", ".wav");
byte audio[] = out.toByteArray();
InputStream input = new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
AudioSystem.write(ais, fileType, file);
//uploading to servlet
FileInputStream in = new FileInputStream(fileToSend);
byte[] buf = new byte[1024];
int bytesread = 0;
String toservlet = "http://localhost:8080/Servlet/upload";
URL servleturl = new URL(toservlet);
URLConnection servletconnection = servleturl.openConnection();
servletconnection.setDoInput(true);
servletconnection.setDoOutput(true);
servletconnection.setUseCaches(false);
servletconnection.setDefaultUseCaches(false);
DataOutputStream out = new DataOutputStream(servletconnection.getOutputStream());
while ((bytesread = in.read(buf)) > -1) {
out.write(buf, 0, bytesread);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error during upload");
}
}
}//End of inner class uploadThread
Here is the code of the grab file method in the servlet:
java.io.DataInputStream dis = null;
try {
int fileLength = Integer.valueOf(request.getParameter("fileLength"));
String fileName = request.getParameter("fileName");
dis = new java.io.DataInputStream(request.getInputStream());
byte[] buffer = new byte[fileLength];
dis.readFully(buffer);
dis.close();
File cibleServeur = new File("/Users/nebrass/Desktop/" + fileName);
FileOutputStream fos = new FileOutputStream(cibleServeur);
fos.write(buffer);
fos.close();
} catch (IOException ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dis.close();
} catch (Exception ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have created a certificate with the keytool. And i have signed the JAR of the applet.
I have added the applet to the jsp file and it is working, and have the all permissions (I tried to save a file on a desktop using the applet)
Update: The problem is that the file is not sent, and when i try to debug the servlet, it is not invoked by the the applet.
Please help
That's not how it works. You've just opened a URLConnection and wrote to the output stream. That way you're assuming something like a socket connection, but here we need more of a HttpUrlConnection and then a request-parameter and a multi-part request.
Google Search
Google found lots of solutions, but for the completeness of the answer, I'm adding one below :
https://stackoverflow.com/a/11826317/566092
You want up upload a file from the server to the user desktop?
I doubt this will be allowed, for obvious security reasons.
Why don't you just call the servlet directly from the browser? And "save as" the file?
Here is an exemple on how to send a file (any type) from a servlet.
protected void doPost(
...
response.setContentType("your type "); // example: image/jpeg, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/octet-stream
response.setHeader("Content-Disposition","attachment; filename=\"your_filename\"");
File uploadedFile = new File("/your_file_folde/your_file_name");
if (uploadedFile.exists()){
FileUtils.copyFile(uploadedFile, response.getOutputStream());
}
else { // Error message
}
....
}

Categories