This is my first question here. I've searched for my doubt. I found similar questions but i haven't exactly got my answer. So please forgive me if i have done something wrong.
I'm trying to save an image from an ImageView in my app to a folder in my sdcard. Here's the code :-
public void save(View view) {
myImage.setDrawingCacheEnabled(true);
Bitmap imgV = myImage.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/AVP_saved");
String fname="Image.png";
File file = new File(myDir, fname);
try {
FileOutputStream out = new FileOutputStream(file);
imgV.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
Toast.makeText(this, "Image Downloaded", 7000).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), 8000).show();
}
}
'save' method is the method assigned to a button. 'myImage' is the ImageView found by its id. I have already set the permissions in the manifest. The thing is, the image dosen't get saved and it says that the path dosen't exist. When I myself create the folder "AVP_saved", then the image gets saved. What do i have to edit in this code such that the app creates the folder by itself when i click the button?
Thanks for your time!
Add this code after File myDir = new File(root + "/AVP_saved");
if(!myDir.exists()) {
mydir.mkdir(); //you can else call mkdirs() if you have to create a complete directory hierarchy
}
It seems that in Java, it's not possible to create a directory hierarchy by creating just a file in it.
With this, you'll create your directory only if it doesn't exist (be careful, if the directory exists but it's a file, it will launch an exception maybe, so you can look for myDir.isDirectory() too).
Related
In my app I am receiving intent to open the pdf file using "application/pdf" intent-filter in menifest.
After a lot of research I am trying following code to open the file.
try {
File f = new File("file://"+uri.getPath());
Toast.makeText(k.this, f.getAbsolutePath(), Toast.LENGTH_LONG).show();
Toast.makeText(k.this, f.exists()?"Y":"N", Toast.LENGTH_LONG).show();
parcelFileDescriptor = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
} catch (IOException e) {
e.printStackTrace();
}
When I click on a file from file manager and open it with my app, It says the file does not exist. That means I am not able to create file from URI.
So my question is how to get parcelFileDescriptor from URI.
Thanks to the comment of Mike M.
getContentResolver().openFileDescriptor()
opens the fileDescriptor correctly.
I am making a Java-SQL database storing app on Eclipse and MySQL. In this app, I have to upload image to the file directory. Currently while making this app, I am using an image upload path and storing all the uploaded images there. But when I'm finished with the app, and if I'm to work it on someone else's computer the image upload path in the code obviously will not work on that computer. What shall I do to make it work on other computer as well? Should I make a prompt which asks for image upload path every time the app opens and store that, or something else?? please help.
private String imageUploadPath = "/home/tsoprano/Documents/eclipse-workspace/enable/src/com/enable/regis/imgupload/";
File file1;
picLabel = new JLabel(" Upload Photo");
picLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
JFileChooser imageChooser= new JFileChooser();
if(imageChooser.showOpenDialog(picLabel)==JFileChooser.APPROVE_OPTION) {
file1 = imageChooser.getSelectedFile();
ImageIcon icon= new ImageIcon(imageChooser.getSelectedFile().getPath());
Image img=icon.getImage().getScaledInstance(130, 150, Image.SCALE_SMOOTH);
icon= new ImageIcon(img);
picLabel.setIcon(icon);
}
}
});
//inside the submit button action
String filePath = imageUploadPath + file1.getName();
try {
BufferedImage bi = ImageIO.read(file1);
ImageIO.write(bi, "jpg", new File(filePath));
} catch (IOException e1) {
e1.printStackTrace();
}
rdto.setPicUrl(filePath);
I would not suggest doing this via a config file, because this is not very user-friendly. Instead, get the current directory (i. e. the one that you executed the java command) using System.getProperty("user.dir"). Then create a new folder inside there, and use it as your upload folder. This will make sure you always have a useable path without bothering the user with specifying it.
I did this small Java project that in it's turn opens different MP3 files. For that I downloaded the JLayer 1.0.1 library and added it to my project. I also added the MP3 files to a package on my project -as well as some JPG images- so as to obtain them from there, and I'm using a hashmap (mapa) and this method to get them:
public static String consiguePath (int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i)).getPath();
}
so as to avoid absolute paths.
When I open an MP3 file I do this:
try {
File archivo = new File(AppUtils.consiguePath(12));
FileInputStream fis = new FileInputStream(archivo);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
Player player = new Player(bis);
player.play();
} catch (JavaLayerException jle) {
}
} catch (IOException e) {
}
The whole thing runs perfectly in NetBeans, but when I build a .jar file and execute it it runs well but it won't open the MP3 files. What called my attention is that it doesn't have trouble in opening the JPG files that are on the same package.
After generating the .jar I checked the MyProject/build/classes/Movimiento folder and all of the MP3 files were actually there, so I don't know what may be happening.
I've seen others had this problem before but I haven't seen any satisfactory answer yet.
Thanks!
Change the consiguePath to return the resulting URL from getResource
public static URL consiguePath(int i) {
return AppUtils.class.getClass().getResource("/Movimiento/" + mapa.get(i));
}
And then use it's InputStream to pass to the Player
try {
URL url = AppUtils.consiguePath(12);
Player player = new Player(url.openStream());
player.play();
} catch (JavaLayerException | IOException e) {
e.printStackTrace();
}
Equally, you could just use Class#getResourceAsStream
Resources are packaged into your Jar file and can no longer be treated as Files
protected void executeInternal(JobExecutionContext context) throws JobExecutionException
{
System.out.println("Sending Birthday Wishes... ");
try
{
for(int i=0;i<maillist.length;i++)
{
Email email = new Email();
email.setFrom("spv_it#yahoo.com");
email.setSubject("Happy IndependenceDay");
email.setTo(maillist[i]);
email.setText("<font color=blue><h4>Dear Users,<br><br><br>Wish you a Happy Independence Day!<br><br><br>Regards,<br>Penna Cement Industries Limited</h4></font>");
byte[] data = null;
ClassPathResource img = new ClassPathResource("newLogo.gif");
InputStream inputStream = img.getInputStream();
data = new byte[inputStream.available()];
while((inputStream.read(data)!=-1));
Attachment attachment = new Attachment(data, "HappyBirthDay","image/gif", true);
email.addAttachment(attachment);
emailService.sendEmail(email);
}
}
catch (MessagingException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is the error I'm getting:
java.io.FileNotFoundException: class path resource [newLogo.gif] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:135)
at com.mail.schedular.BirthdayWisherJob.executeInternal(BirthdayWisherJob.java:55)
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:66)
at org.quartz.core.JobRunShell.run(JobRunShell.java:223)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
The best practise is to read/write or to provide reference of any file is by mentioning the ABSOLUTE PATH of that file.
To your question, It shows the FileNotFoundException because, JVM failed to locate the file in your current directory which is by default your source path. So provide the absolute path in ClassPathResource or copy that image file to your current directory. It will solve your problem.
I think you need to put your file inside inside the src folder , if it's there then check whether it's under some directory which is inside the src directory.
Then give the correct location like given details below
src[dir]----->newLogo.gif
ClassPathResource img = new ClassPathResource("newLogo.gif");
or,
src[dir]----->images[dir]---->newLogo.gif
ClassPathResource img = new ClassPathResource("/images/newLogo.gif");
You got this error since the job is running in a separate quartz thread, I suggest that you locate your file newLogo.gif outside the jar and use the following to load it.
Thread.currentThread().getContextClassLoader().getResource("classpath:image/newLogo.gif");
I'm trying to share an image file which saved to internal storage using share intent.
after I intent image file doesn't display.
I used following code to save the image file
try {
FileOutputStream fos = openFileOutput("twitterimage.jpg", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
bikeBm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
}
//intent code
File internalFile = getFileStreamPath("twitterimage.jpg");
Uri uri = Uri.fromFile(internalFile);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,new File(uri));
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
when I check the file existance using above "uri", the image file exists
in the internal storage but checking the file using
String file = "data/data/com.bike.app/twitterimage.jpg";
File f = new File(file);
shows me the file not exist.
pls help me to solve this problem.
If i am gessing right you want to share images between to applications. Your probleme is that you used Context.MODE_PRIVATE when you write a file so other applications cannot have access to this file.
To share an image you can use MediaProvider to restrict access to you Media or simply used Context.MODE_WORLD_READABLE but the file will be public readable then.
hope that help