Here is I want to make. I want to make an app, for example it has a button that will download a certain video file and put it on the resource(raw) folder. Is it possible?
Short answer : You can not.
You can not, under any circumstance, write/dump a file to the raw/assets folder in runtime.
What you can do is to download the video and store it into Internal Memory (application reserved storage) or External Memory (usually your SDCard))
For example, you can store media files, for instance a Bitmap to your external storage like this.
private void saveAnImageToExternalMemory(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "yourimagename.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And equally, read an file, in this example an image (which is then loaded to an imageView), from external memory
private void loadImageFromStorage(String path){
try {
File f=new File(path, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Edit: Additionally, you can store your data into internal memory
Alternatively you can also save the Bitmap to the internal storage in
case the SD card is not available or for whatever other reasons you
may have. Files saved to the internal storage are only accessible by
the application which saved the files. Neither the user nor other
applications can access those files
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = context.openFileOutput("yourimage.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
Check this documentation for more information
Regards,
Related
This spring app performs simple file upload,
here's the controller class
#Override
public String fileUpload(MultipartFile file) {
try{
// save uploaded image to images folder in root dir
Files.write(Paths.get("images/"+ file.getOriginalFilename()), file.getBytes());
// perform some tasks on image
return "";
} catch (IOException ioException) {
return "File upload has failed.";
} finally {
Files.delete(Paths.get("images/" + file.getOriginalFilename()));
}
}
but when i build jar and runs, it throws IOException saying,
java.nio.file.NoSuchFileException: images\8c9.jpeg.
So my question is how can i add the images folder inside the jar executable itself.
Thanks.
You should provide a full path for the images folder, or save in java.io.tmpdir creating the image folder first.
But, in my opinion you should configure your upload folder from a config file for flexibility. Take a look at this.
app:
profile-image:
upload-dir: C:\\projs\\web\\profile_image
file-types: jpg, JPG, png, PNG
width-height: 360, 360
max-size: 5242880
In your service or controller, do whatever you like, may be validate image type, size etc and process it as you like. For instance, if you want thumbnails(or avatar..).
In your controller or service class, get the directory:
#Value("${app.image-upload-dir:../images}")
private String imageUploadDir;
Finally,
public static Path uploadFileToPath(String fullFileName, String uploadDir, byte[] filecontent) throws IOException {
Path fileOut = null;
try{
Path fileAbsolutePath = Paths.get(StringUtils.join(uploadDir, File.separatorChar, fullFileName));
fileOut = Files.write(fileAbsolutePath, filecontent);
}catch (Exception e) {
throw e;
}
return fileOut; //full path of the file
}
For your question in the comment: You can use java.io.File.deleteOnExit() method, which deletes the file or directory defined by the abstract path name when the virtual machine terminates. TAKE A GOOD CARE THOUGH, it might leave some files if not handled properly.
try (ByteArrayOutputStream output = new ByteArrayOutputStream();){
URL fileUrl = new URL(url);
String tempDir = System.getProperty("java.io.tmpdir");
String path = tempDir + new Date().getTime() + ".jpg"; // note file extension
java.io.File file = new java.io.File(path);
file.deleteOnExit();
inputStream = fileUrl.openStream();
ByteStreams.copy(inputStream, output); // ByteStreams - Guava
outputStream = new FileOutputStream(file);
output.writeTo(outputStream);
outputStream.flush();
return file;
} catch (Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch(Exception e){
//skip
}
}
I got a FileNotFoundException#5818 when I try to get a file address using getExternalStoragePublicDirectory().
This is my method copied from Google Dev Documentation:
public File getPublicDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e("PUBLIC DIRECTORY", "Directory not created");
}
return file;
}
I call this method here:
try{
FileOutputStream fos=new FileOutputStream(getPublicDir("mySnapshot"));
Boolean success=snapshot.compress(Bitmap.CompressFormat.PNG, 100, fos);
Toast.makeText(MainActivity.this,"Compress?
:"+success,Toast.LENGTH_SHORT).show();
fos.close();
}catch(IOException e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"NOT SAVED",Toast.LENGTH_SHORT).show();
}
I am not exactly sure what albumName is. Is it the name of the folder to be created or the name of the photo file to be stored?
Here is a screenshot of the error it throws when I was debugging:
It throws the error at line "FileOutputStream fos=new FileOutputStream(getPublicDir("mySnapshot"));."
Write permission added.
Here is what my app looks like (GIF), and the error it throws:
This is where I create a folder (GIF):\
I found here a way to write text into directory, it works but it's only for text:
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
myExternalFile = new File(getExternalFilesDir(filepath), filename);
private String filename = "SampleFile.txt";
private String filepath = "MyFileStorage";
I am trying to use a method to generate a bitmap from Layouts and save the bitmap to a file in the internal memory. However, the getApplicationContext() is not resolved.
Here is the code for the method
private void generateAndSaveBitmap(View layout) {
//Generate bitmap
layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap imageToSave = layout.getDrawingCache();
//Create a file and path
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File fileName = new File(directory, "sharableImage.jpg");
if (fileName.exists())
fileName.delete();
//Compress and save bitmap under the mentioned fileName
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileName);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// return directory.getAbsolutePath();
}
Used some help from StackOverFlow codes to generate this method. Even after reading related queries on getApplicationContext(), I am unable to find the issue. Any help would be really appreciated
EDIT : Forgot to mention, that the method generateAndSaveBitmap(View layout) is defined inside a separate class
Regards
Step #1: Delete ContextWrapper cw = new ContextWrapper(getApplicationContext());, as you do not need it.
Step #2: Replace cw.getDir("imageDir", Context.MODE_PRIVATE); with layout.getContext().getDir("imageDir", Context.MODE_PRIVATE);
Also, please move this disk I/O to a background thread.
Try ,
ContextWrapper cw = new ContextWrapper(getActivity());
incase it's a fragment.
Have you tried:
File dir = getApplicationContext().getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
Now, from the image processing to the write of the file into the directory everything should be done off thread. Encapsulate it in an AsyncTask when possible and within it move generateAndSaveBitmap() method to it.
there is a text file that an application produces, I would like to take that file and read it as strings in my application. How can I achieve that, any help would be grateful. Both applications are my applications so I can get the permissions.
Thank you!
This is possible using the standard android-storage, where all the user's files are stored too:
All you need to do is to access the same file and the same path in both applications, so e.g.:
String fileName = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/myFileNameForBothApplications.txt";
Where myFolderForBothApplications and myFileNameForBothApplications can be replaced by your folder/filename, but this needs to be the same name in both applications.
Environment.getExternalStorageDirectory() returns a File-Object to the common, usable file-directory of the device, the same folder the user can see too.
By calling the getPath() method, a String representing the path to this storage is returned, so you can add your folder/filenames afterwards.
So a full code example would be:
String path = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/";
String pathWithFile = path + "myFileNameForBothApplications.txt";
File dir = new File(path);
if(!dir.exists()) { //If the directory is not created yet
if(!dir.mkdirs()) { //try to create the directories to the given path, the method returns false if the directories could not be created
//Make some error-output here
return;
}
}
File file = new File(pathWithFile);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
//File couldn't be created
return;
}
Afterwards, you can write in the file or read from the file as provided e.g. in this answer.
Note that the file stored like this is visible for the user and my be edited / deleted by the user.
Also note what the JavaDoc for the getExternalStorageDirectory() says:
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
I do not know if this is the best/safest way to fix your problem, but it should work.
You can save the text file from your assets folder to anywhere in the sdcard, then you can read the file from the other application.
This method uses the getExternalFilesDir, that returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
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);
}
}
And to read:
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
I want to be able to open a PDF file when the user clicks on 'HELP' in my application. The PDF file is located with the JAR, extracted to a tmp directory and then selected to open by awt.Desktop.getDesktop () (to allow for windows and linux use).
When I run the app from Eclipse then it works fine, the PDF opens with no errors. When I export to JAR and run then I get an error stating the 'PDF document is damaged', if I navigate manually to the PDF document (on my ubuntu machine /tmp/546434564.pdf) then I get the same error when I try to open the file. I am confused what is going on. The file size of the 'damaged' PDF is the same as the working one, so I dont think it is a permission issue.
The code I am using is:
public Main() throws FontFormatException, IOException {
//lets load the font
Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("/Coalition_v2.ttf")).deriveFont(Font.PLAIN, 14);
System.out.println(font);
//lets write the tmp file for help to the machine now
try {
java.io.InputStream iss = getClass().getResourceAsStream("/nullpdf.pdf"); //update the filename here when the help guide is written
byte[] data = new byte[iss.available()];
iss.read(data);
iss.close();
String tempFile = "file";
File temp = File.createTempFile(tempFile, ".pdf");
FileOutputStream fos = new FileOutputStream(temp);
fos.write(data);
fos.flush();
fos.close();
tmphelpfile = temp.getAbsolutePath();
System.out.println(tmphelpfile);
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("TEMP FILE NOT CREATED - ERROR in tmp file writing");
}
And then to call the pdf:
JMenu mnHelpGuide = new JMenu("Help Guide");
mnHelpGuide.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
// Help();
Desktop d = java.awt.Desktop.getDesktop ();
try {
System.out.println(tmphelpfile);
d.open (new java.io.File (String.valueOf(tmphelpfile)));
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println("Couldnt open your file - error on HELP Guide");
e1.printStackTrace();
}
}
});
Thanks for the help guys. The problem was fixed by importing the ApachecommonsIO jar and then modifying the code to this:
try {
java.io.InputStream iss = getClass().getResourceAsStream("/nullpdf.pdf"); //update the filename here when the help guide is written
// byte[] data = new byte[iss.available()];
byte[] data = IOUtils.toByteArray(iss);
iss.read(data);
iss.close();
String tempFile = "file";
File temp = File.createTempFile(tempFile, ".pdf");
FileOutputStream fos = new FileOutputStream(temp);
fos.write(data);
fos.flush();
fos.close();
tmphelpfile = temp.getAbsolutePath();
System.out.println(tmphelpfile);
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("TEMP FILE NOT CREATED - ERROR in tmp file writing");
}