How To Copy File From SD to Local Storage on Android - java

I know with Kit Kat you can only write to your applications package specific directory on SD Cards. I was however under the impression you could still copy files from an SD card to local storage with the:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am simply testing if I can copy one file. If I am able to do that I will add the code to search the entire SD card DCIM folder. For now I have the following code (please forgive the messiness of the code, I have written C# and vb.net but java is still very new to me):
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "TCM";
File projDir = new File(dirPath);
if (!projDir.exists())
projDir.mkdirs();
String CamPath = projDir + File.separator + tv2.getText();
File projDir2 = new File(CamPath);
if (!projDir2.exists())
projDir2.mkdirs();
File LocalBuck = new File(projDir2 + File.separator );
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath();
File directory1 = new File (sdCard.getAbsolutePath() + "/DCIM");
File directory = new File(directory1 + "/100SDCIM");
File Buckfile = new File(directory, "/BigBuck.jpg");
try {
exportFile(Buckfile, LocalBuck);
} catch (IOException e) {
e.printStackTrace();
}
Here is my code for the export function/application:
private File exportFile(File src, File dst) throws IOException {
//if folder does not exist
if (!dst.exists()) {
if (!dst.mkdir()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(new Date());
File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//Straight to Error Handler
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(expFile).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
return expFile;
}
Here is what my emulator looks like:
Looking for: Debug of SD Location
Should Find It?: EmulatorShowingSd
Question: Am I even able to copy a file from the SD card to local storage after KitKat; if so what is wrong in the code causing the exception to be thrown when it tries to access the SD card file?

Related

How to use File.move ()

I would like to move a file from the download folder to a folder in my app, I have seen that you can use the Files.move (source, destination) function, but I don't know how to get the source and destination path.
When y try
String sdCard = Environment.getExternalStorageDirectory().toString();
File ficheroPrueba = new File(sdCard + "/pau_alem18je_compressed.pdf");
if(ficheroPrueba.exists())
Log.v(TAG, "Hola")
}
Despite having downloaded the file (it is seen in the android emulator in downloads) it does not print the log.v
Use Environment.getExternalStorageDirectory() to get to the root of external storage (which, on some devices, is an SD card).
String sdCard = Environment.getExternalStorageDirectory().toString();
// the file to be moved or copied
File sourceLocation = new File (sdCard + "/sample.txt");
// make sure your target location folder exists!
File targetLocation = new File (sdCard + "/MyNewFolder/sample.txt");
// just to take note of the location sources
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else{
// make sure the target file exists
if(sourceLocation.exists()){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
}else{
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

Android 5+ File saved "incorrect"

I wrote a small Android App to record audio and save this on the disk of the smartphone. Now I've got the problem that it's saved on the wrong location with the wrong name and I can't see why. (I'm relative new to Android programming)
public void startRecording(View view) {
File folder = new File(Environment.getExternalStorageDirectory() + "/" + R.string.app_name);
file_name = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + R.string.app_name;
if(!folder.exists()) {
boolean created = folder.mkdirs();
if(!created) { Log.i(LOG_TAG, "Could not create folder/s."); return; }
}
if(editText.getText() != null)
file_name += editText.getText() + ".3gp";
else
file_name += Calendar.getInstance().getTime() + ".3gp";
outputFile = new File(file_name);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(file_name);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
Toast.makeText(CaptureActivity.this, R.string.toast_recording_start, Toast.LENGTH_SHORT).show();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
Toast.makeText(CaptureActivity.this, R.string.toast_recording_failed, Toast.LENGTH_LONG).show();
mediaRecorder = null;
}
}
The file should be saved in a folder called TrueCapture and the file itself should be called ggj.3gp .
But the file is saved on the internal storage under the name 2131099680ggj.3gp .
The next problem there is, I can only find the file with the explorer app from my smartphone. The PC can't find the file and no other app.
Some Details:
Android 6
File Name is wrong (2131099680ggj.3gp instead of ggj.3gp)
File is saved in internal storage in no specific folder instead of the external storage (SD card is in the smartphone) in a new folder called "TrueCapture"
No other app seems to know about this file except for the explorer app of the smartphone
R.string.app_name is the ID assigned to your resource in the R class, an int.
To get your String resource, you might wanna use the getString() method of Context.
Something like this should work:
String ext = ".3gp";
File folder = new File(Environment.getExternalStorageDirectory() + "/" + getString(R.string.app_name));
if(!folder.exists()) {
folder.mkdirs();
}
file_name = folder.getAbsolutePath() + "/";
if(editText.getText().length() > 0) {
file_name += editText.getText().toString() + ext;
} else {
file_name += Calendar.getInstance().getTimeInMillis() + ext;
}
File outputFile = new File(file_name);
// ...
You also need to add the WRITE_EXTERNAL_STORAGE permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Java - Getting specific folder and files from zip file

So I am working on an Android app and what I am trying to do is make it so a user selects a zip file, it extracts the contents of it into an apk and installs the modified APK for the user. Right now all the files in the zip file have to be in the root of the zip file for it to work, if there is a directory and than the files I need it will not work. I am trying to make it scan for, for example the 'assets' folder and than get the directory its located in and copy all the files from that directory. I've tried extracting the files first and scanning using a loop, and for some reason had no success doing that, and it was time consuming anyways. If you know any libraries or could point me in the right direction that would be great! Thanks!
BTW you can extract all the files from zip folder like below. i.e
private String unpackZip(String path, String zipname) {
String apkfilename = "";
InputStream is;
ZipInputStream zis;
try {
String filename;
is = new FileInputStream(path + "/" + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + "/" + filename);
fmd.mkdirs();
continue;
}
// This condition is to only extract the apk file
if (filename.endsWith(".apk")) {
apkfilename = filename;
FileOutputStream fout = new FileOutputStream(path + "/"
+ filename);
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
}
zis.close();
} catch (IOException e) {
e.printStackTrace();
return apkfilename;
}
return apkfilename;
}
//To install the apk file call the method
String apkfilename=unpackZip(Environment.getExternalStorageDirectory()
.getPath(), "temp.zip");
try {
File file = new File(Environment.getExternalStorageDirectory()
.getPath(), apkfilename);
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(
Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(promptInstall);
} catch (Exception e) {
e.printStackTrace();
}
//Also add the read write permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

I keep getting java.io.FileNotFoundException with my zip extractor

Could anybody help me with my java zip extractor as stated in the title I keep getting java.io.FileNotFoundException on the folders with files in them
public void UnZip() {
try {
byte[] data = new byte[1000];
int byteRead;
BufferedOutputStream bout = null;
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
String filename = entry.getName();
File newfile = new File(Deobf2 + File.separator + filename);
System.out.println("file unzip : " + newfile.getAbsoluteFile());
new File(newfile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newfile);
int len;
while ((len = zin.read(data)) > 0) {
fos.write(data, 0, len);
}
fos.close();
entry = zin.getNextEntry();
}
zin.closeEntry();
zin.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
error log
http://pastebin.com/crMKaa37
values
static String tempDir = System.getProperty("java.io.tmpdir");
public static File Deobf = new File(tempDir + "Deobf");
public static String Deobf2 = Deobf.toString();
entire code paste
http://pastebin.com/1vTfABR1
I have copy pasted same code and it is working fine. I think u dont have administrator permission on C drive. login As Administrator and run . it will work.
Access Denied Exception will come when u don have administrator level of permission on C drive.
The problem is Your doing
String Deobf2 = Deobf.toString();//this does not give the location of the file
use
file.getAbsolutePath();
in your case Deobf.getAbsolutePath();
instead. Check http://www.mkyong.com/java/how-to-get-the-filepath-of-a-file-in-java/
if you want to get the path only till the parent directory check this How to get absolute path of directory of a file?
Problem fixed changed some code
for anyone whos wants a copy of the working zip extraction code here you go http://pastebin.com/bXL8pUSg
The variable Deobf2 in the output of the zip

Android: Cant copy sub directory of sub directory in assets folder

I'm trying to copy some preloaded content stored in the assets folder of my app to the sdk card. Problem is I cant seem to get hold of the file path to the directory I want to copy. I want to loop through the preloadedcontent folder stored in my assets folder in the project, then copy each folder inside it across to the sdk card. I can loop through the preloaded content file names ok, but get a filenotfound exception when i try to copy the directory across:
- Assets/
-- preloadedcontent/
--- 112/
--- 113/
--- 114/
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("preloadedcontent");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
Log.d("file: ",filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("preloadedcontent/" + filename + "/");
File outFile = new File(_DirectoryName, filename);
out = new FileOutputStream(outFile);
//copyFile(in, out);
File f = stream2file(in,filename);
copyDirectory(f,outFile);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
error is on this line assetManager.open("preloadedcontent/" + filename + "/");
That's because "preloadedcontent/" + filename + "/" is not a valid file name (due to the trailing slash).
AssetManager#open() requires the name of a single file to open.
if(id.equals("AABA / ABO")){
AssetManager assetManager = activity.getAssets();
String[] files;
try {
files = assetManager.list("aaba");
List<String> it = Arrays.asList(files);
for (String string : it) {
InputStream ims = assetManager.open("aaba/" + string);
// create drawable from stream
Drawable d = Drawable.createFromStream(ims, null);
drawable.add(d);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Categories