How to access /data folder of another application through your application? - java

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");

Related

Jar executable of spring app file upload failed?

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
}
}

Downloading files from a server and put it to /raw folder

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,

Downloading files(.zip, .jar,...) to a folder

I have been trying many ways of downloading a file from a URL and putting it in a folder.
public static void saveFile(String fileName,String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
boolean success = (new File("File")).mkdirs();
if (!success) {
Status.setText("Failed");
}
try {
saveFile("DownloadedFileName", "ADirectDownloadLinkForAFile");
} catch (MalformedURLException ex) {
Status.setText("MalformedURLException");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Status.setText("IOException Error");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
}
I found this code on the net, am i using it correctly?
If i did:
saveFile("FolderName", "ADirectDownloadLinkForAFile")
I would get IOException error
What I want my code to do is:
Create folder
Download file
Downloaded file to go to the just created folder
I'm a newbie here sorry. Please help
There are various ways in java to download a file from the internet.
The easiest one is to use a buffer and a stream:
File theDir = new File("new folder");
// if the directory does not exist, create it
if (!theDir.exists())
{
System.out.println("creating directory: " + directoryName);
boolean result = theDir.mkdir();
if(result){
System.out.println("DIR created");
}
}
FileOutputStream out = new FileOutputStream(new File(theDir.getAbsolutePath() +"filename"));
BufferedInputStream in = new BufferedInputStream(new URL("URLtoYourFIle").openStream());
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
Just the basic concept. Dont forget the close the streams ;)
The File.mkdirs() statement appears to be creating a folder called Files, but the saveFile() method doesn't appear to be using this, and simply saving the file in the current directory.

Saving file as a different name

I have a Java form in which you can select a file to open. I have that file:
File my_file = ...
I want to be able to save my file as a different name.
how can I do it using "File my_file"?
I tried:
File current_file = JPanel_VisualizationLogTab.get_File();
String current_file_name = current_file.getName();
//String current_file_extension = current_file_name.substring(current_file_name.lastIndexOf('.'), current_file_name.length()).toLowerCase();
FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fileDialog.setFile(current_file_name);
fileDialog.setVisible(true);
But that doesn't save the file.
I would recommend using the Apache Commons IO library to make this task easier. With this library, you could use the handy FileUtils class that provides many helper functions for handling file IO. I think you would be interested in the copy(File file, File file) function
try{
File current_file = JPanel_VisualizationLogTab.get_File();
File newFile = new File("new_file.txt");
FileUtils.copyFile(current_file, newFile);
} catch (IOException e){
e.printStackTrace();
}
Documentation
If you want to copy it with a different name, i found this piece of Code via google
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
now you can call it with
File inF = new File("/home/user/inputFile.txt");
File outF = new File("/home/user/outputFile.txt");
copyFile(inF, outF);
it´s just important that both Files exist, otherswise it will raise an exception
You can rename the file name.
Use:
myfile.renameTo("neeFile")
There is a Method called renameTo(new File("whatever you want")); for File Objects

How to move/rename file from internal app storage to external storage on Android?

I am downloading files from the internet and saving the streaming data to a temp file in my app's internal storage given by getFilesDir().
Once the download is complete, I need to move the temp file to my download directory on External Memory (usually an SD Card). For some reason though, File.renameTo() isn't working for this. I'm guessing there's a problem because it's two separate file systems, but I can still download directly to the SD Card and the file URIs are correct.
Is there another simple and quick way to transfer that file from internal memory to external or do I have to do a byte stream copy and delete the original?
To copy files from internal memory to SD card and vice-versa using following piece of code:
public static void copyFile(File src, File dst) throws IOException
{
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
And - it works...
Internal and external memory is two different file systems. Therefore renameTo() fails.
You will have to copy the file and delete the original
After you copy the file (as #barmaley's great answer shows), don't forget to expose it to the device's gallery, so the user can view it later.
The reason why it has to be done manually is that
Android runs a full media scan only on reboot and when (re)mounting
the SD card
(as this guide shows).
The easier way to do this is by sending a broadcast for the scanning to be invoked:
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(outputFile));
context.sendBroadcast(intent);
And voila! You can now view your file in the device's gallery.
An alternative to the copying using your own function is to use Apache's library's class "FileUtils" , in the function called copyFile :
FileUtils.copyFile(src, dst, true);
Did some trivial modifications to #barmaley's code
public boolean copyFile(File src, File dst) {
boolean returnValue = true;
FileChannel inChannel = null, outChannel = null;
try {
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(dst).getChannel();
} catch (FileNotFoundException fnfe) {
Log.d(logtag, "inChannel/outChannel FileNotFoundException");
fnfe.printStackTrace();
return false;
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IllegalArgumentException iae) {
Log.d(logtag, "TransferTo IllegalArgumentException");
iae.printStackTrace();
returnValue = false;
} catch (NonReadableChannelException nrce) {
Log.d(logtag, "TransferTo NonReadableChannelException");
nrce.printStackTrace();
returnValue = false;
} catch (NonWritableChannelException nwce) {
Log.d(logtag, "TransferTo NonWritableChannelException");
nwce.printStackTrace();
returnValue = false;
} catch (ClosedByInterruptException cie) {
Log.d(logtag, "TransferTo ClosedByInterruptException");
cie.printStackTrace();
returnValue = false;
} catch (AsynchronousCloseException ace) {
Log.d(logtag, "TransferTo AsynchronousCloseException");
ace.printStackTrace();
returnValue = false;
} catch (ClosedChannelException cce) {
Log.d(logtag, "TransferTo ClosedChannelException");
cce.printStackTrace();
returnValue = false;
} catch (IOException ioe) {
Log.d(logtag, "TransferTo IOException");
ioe.printStackTrace();
returnValue = false;
} finally {
if (inChannel != null)
try {
inChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
if (outChannel != null)
try {
outChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnValue;
}
Picture that:
This is internal path : pathInternal
And this is external path :
pathExternal
Try with this code:
public void moveIn (String pathInternal, String pathExternal) {
File fInternal = new File (pathInternal);
File fExternal = new File (pathExternal);
if (fInternal.exists()) {
fInternal.renameTo(fExternal);
}
}
You can do it using operations with byte[]
define in your class:
public static final String DATA_PATH =
Environment.getExternalStorageDirectory().toString() + "/MyAppName/";
then:
AssetManager assetManager = context.getAssets();
InputStream in = assetManager.open("data/file.txt");
OutputStream out = new FileOutputStream(DATA_PATH + "data/file.txt");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
For Move file best way is Renaming it's path with different path and name
example:
File from = new File(Environment.getExternalStorage().getAbsolutePath()+"/kaic1/imagem.jpg");
File to = new File(Environment.getExternalStorage().getAbsolutePath()+"/kaic2/imagem.jpg");
from.renameTo(to);

Categories

Resources