Android dropbox upload/download app to an SD card - java

I'm trying to make an app that uploads a file to dropbox and downloads it.
Uploading seems to work, downloading doesn't. Also it doesn't actually upload from my SD card but from my phone internal memory.
saveOnDropbox() uploads a file.txt from phone/MyFiles/file.txt to dropbox app folder.
saveOnDevice() - something happens when I use this, but the file doesn't get neither to my phone or SD card
public void saveOnDropBox() throws IOException, DropboxException {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + "/MyFiles/file.txt");
FileInputStream inputStream = new FileInputStream(file);
DropboxAPI.Entry response = dropboxAPI.putFile("/file.txt", inputStream,
file.length(), null, null);
Log.i("D bExam pleLog", "The uploaded file's rev is: " + response.rev);
}
public void saveOnDevice() {
FileOutputStream outputStream = null;
try {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + "/MyFiles/file.txt");
outputStream = new FileOutputStream(file);
DropboxAPI.DropboxFileInfo info = dropboxAPI.getFile("/file.txt", null, outputStream, null);
} catch (Exception e) {
System.out.println("Som ething w ent w rong: " + e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
System.out.println("___" + e);
}
}
}
}}
Appreciate any help.

Related

How do I create a file in the Downloads folder on android?

I am trying to download a file from an FTP server and save it to a file in the Downloads folder. In the emulator (since there is an AndroidAPI 30) it gives a Permission Denied, apparently because
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
is outdated. How else can I save the file to the Downloads folder?
Here is the code to create the file:
public void downloadFile() {
String filename = this.filename;
new Thread(new Runnable() {
#Override
public void run() {
FTPClient client = new FTPClient();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
try {
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
client.connect("backup-storage5.hostiman.ru");
client.enterLocalPassiveMode();
client.login("*********", "********");
client.retrieveFile("/" + filename, outputStream);
client.logout();
client.disconnect();
System.out.println("ALL GOOD!");
} catch (IOException e) {
System.out.println("FAILED TO DOWNLOAD FILE FROM SERVER!{n" + e);
}
}
}).start();
}

Android 10 does not save text file

I generated a text file and tried to save it. It doesn't work only on android Q. On android 9 , 8 and 7 it works. When I check if file exists on android 10 it works but I don't it on device . I do this :
private void createFile(Context ctx, String fileName, String text) {
File filesDir = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
filesDir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
}
assert filesDir != null;
if (!filesDir.exists()){
if(filesDir.mkdirs()){
}
}
File file = new File(filesDir, fileName + ".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
throw new IOException("Cant able to create file");
}
}
OutputStream os = new FileOutputStream(file);
byte[] data = text.getBytes();
os.write(data);
os.flush();
os.close();
Log.e("TAG", "File Path= " + file.toString());
if(file.exists()){
Log.e("d","d");
}
File fileTemp = new File(file.getPath());
FileInputStream notes_xml = new FileInputStream(fileTemp);
byte fileContent[] = new byte[(int)notes_xml.available()];
//The information will be content on the buffer.
notes_xml.read(fileContent);
String strContent = new String(fileContent);
Log.e("content",strContent);
notes_xml.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Android: File written in external storage is not showing

I'm trying to write a text file and save it in the android external storage, but file is not showing and I don't get any errors.
Here is my code:
String r;
String fname= "readme.txt";
r = Environment.getExternalStorageDirectory().toString();
File myDir = new File(r);
if (!myDir.exists()) {
myDir.mkdirs();
}
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
Out.write(wfile)
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Try something below. You can add validations to check whether file exists or not, as you please.
File file = new
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "readme.txt");
FileOutputStream out = new FileOutputStream(file);
out.write(wfile);
out.flush();
out.close();
MediaScannerConnection.scanFile(mContext, new String[] { file.toString() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Just FYI, Environment.DIRECTORY_DOCUMENTS may does not exists in older android versions. Then you may have to add a validation to check that and create a directory if not.

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

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

java.io.FileNotFoundException when trying to copy a image from Photos app

I'm trying to get a image from android Photos app using the share option that point to my PhotoGetFromGallery activity. Here is the code:
public void copy(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
String sourcePath = getRealPathFromURI(imageUri);
if(isExternalStorageWritable()) {
if (imageUri != null) {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
String destinationImagePath = sd + "/Pictures/MyAppImgFolder/";
File source = new File(data, sourcePath);
String fileName = source.getName();
File destination = new File(sd, destinationImagePath + fileName);
try {
copy(source, destination);
} catch (Exception e) {
Log.e("COPY IMAGE ERROR", e.toString() + ". Destination Path is " + destinationImagePath.toString() + " and Source path is "+ sourcePath);
}
}
}
}
sourcePath string returns the correct image path (ex. /storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg). However, I'm getting the FileNotFoundException because Environment.getDataDirectory() returns /data/storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg.
Here is my log:
E/COPY IMAGE ERRORīš• java.io.FileNotFoundException: /data/storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg: open failed: ENOENT (No such file or directory). Destination Path is /storage/emulated/0/Pictures/MyAppImgFolder/ and Source path is /storage/emulated/0/Pictures/Instagram/IMG_20150413_114608.jpg
Here is my AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
My question is how can I get, if possible, any path of images stored at Photos app or Android Gallery?
You should not be using getDataDirectory - you are already being handed a complete path, starting with "/storage" Use the single argument File() constructor passing only the sourcePath, like this:
File sd = Environment.getExternalStorageDirectory();
String destinationImagePath = sd + "/Pictures/MyAppImgFolder/";
//sourcePath is already a full path name
File source = new File(sourcePath);
//redundant String fileName = source.getName();
File destination = new File(destinationImagePath + sourcePath);
//You are proposing many new subdirectories, so you must create them
destination.getParentFile()makeDirs();
//now you can continue with your copy attempt
I managed to solve the problem. Follows the code that works . Thanks to Chris Stratton for guiding me in this matter.
File sd = Environment.getExternalStorageDirectory();
String destinationImagePath = sd + AppConstant.PHOTO_ALBUM;
File imagePath = new File(destinationImagePath);
File source = new File(sourcePath);
String fileName = source.getName();
File destination = new File(destinationImagePath + fileName);
if (!imagePath.exists()) {
imagePath.mkdirs();
try {
copy(source, destination);
Toast.makeText(getApplicationContext(), "Success! File was copy from " + sourcePath + " to " + destinationImagePath, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("COPY IMAGE ERROR", e.toString());
}
} else if(destination.exists() && !destination.isDirectory()){
Toast.makeText(getApplicationContext(), "Image is already on your image folder", Toast.LENGTH_LONG).show();
}

Categories

Resources