SOLVED:
ok so I am basically stupid. I couldn't open the file because I forgot to install winrar or 7zip since this pc is newly formatted... Everything works fine. Sorry to waste anyone's time.
In my app I programmatically generate a .zip file from photos and .csv files in a directory.
It creates the zip and then sends the email with the attachment without a hickup. The problem however is that on my pc I can't extract the .zip file because it says it's invalid, but on my device using "WinZip" I can check my .zip file and it has everything it is suppose to have. This is confusing me.
Here is my code:
Here I check for which checkboxes have been checked then do the zipping
for(int i = 0; i < cbStates.size(); ++i)
{
if(cbStates.get(i))
{
String zipFile = Environment.getExternalStorageDirectory() + "/ArcFlash/" + listItems.get(i) + ".zip";//ex: /storage/sdcard0/ArcFlash/study12.zip
String srcDir = Environment.getExternalStorageDirectory() + "/ArcFlash/" + listItems.get(i);
try
{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File srcFile = new File(srcDir);
Log.i("customException", "going to compress");
addDirToArchive(zos, srcFile);
// close the ZipOutputStream
zos.close();
}
catch (IOException ioe)
{
System.out.println("Error creating zip file: " + ioe);
}
//Send the email
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"jbasson#powercoreeng.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Test Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "From My App");
String folderPath = Environment.getExternalStorageDirectory() + "/ArcFlash/" + listItems.get(i) + ".zip";
//Uri u = Uri.fromFile(folderPath);
//Log.i("customException", "uri path: " + u.getPath());
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + folderPath));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
Toast.makeText(context,"Case \"" + studyName + "\" has been sent", Toast.LENGTH_LONG).show();
//adapter.setElement(i, adapter.getStudy(i) + "(sent)");
}
}
and here is the zip function:
private static void addDirToArchive(ZipOutputStream zos, File srcFile)
{
File[] files = srcFile.listFiles();
Log.i("customException", "Adding directory: " + srcFile.getName());
for (int i = 0; i < files.length; i++)
{
// if the file is directory, use recursion
if (files[i].isDirectory())
{
addDirToArchive(zos, files[i]);
continue;
}
try
{
System.out.println("tAdding file: " + files[i].getName());
// create byte buffer
byte[] buffer = new byte[2048];//1024
FileInputStream fis = new FileInputStream(files[i]);
zos.putNextEntry(new ZipEntry(files[i].getAbsolutePath() + "/" + files[i].getName()));//files[i].getName()
int length;
while ((length = fis.read(buffer)) > 0)
{
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
catch (Exception ex)
{
Log.i("customException", "error zipping: " + ex.getMessage());
}
}
}
ok so I am basically stupid. I couldn't open the file because I forgot to install winrar or 7zip since this pc is newly formatted...
Related
Our team is creating a chatbot application this week. We finished coding the AIML files as well as the main codes in Android Studio. The only problem we have right now is the link between these two.
I've already placed the Ab.jar in the libs folder. Also, I've placed the AIML files in the assets folder.
Assets folder
The codes I think are relevant to linking are the following (from ChatActivity.class):
//checking SD card availability
boolean a = isSDCARDAvailable();
//receiving the assets from the app directory
AssetManager assets = getResources().getAssets();
File seedletDir = new File(Environment.getExternalStorageDirectory().toString() + "/bots/seedlet");
boolean b = seedletDir.mkdirs();
if (seedletDir.exists()) {
//Reading the file
try {
for (String dir : assets.list("seedlet")) {
File subdir = new File(seedletDir.getPath() + "/" + dir);
boolean subdir_check = subdir.mkdirs();
for (String file : assets.list("seedlet/" + dir)) {
File f = new File(seedletDir.getPath() + "/" + dir + "/" + file);
if (f.exists()) {
continue;
}
InputStream in = null;
OutputStream out = null;
in = assets.open("seedlet/" + dir + "/" + file);
out = new FileOutputStream(seedletDir.getPath() + "/" + dir + "/" + file);
//copy file from assets to the mobile's SD card or any secondary memory
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
//get the working directory
MagicStrings.root_path = Environment.getExternalStorageDirectory().toString() + "/seedlet";
System.out.println("Working Directory = " + MagicStrings.root_path);
AIMLProcessor.extension = new PCAIMLProcessorExtension();
//Assign the AIML files to bot for processing
bot = new Bot("seedlet", MagicStrings.root_path, "chat");
chat = new Chat(bot);
String[] args = null;
mainFunction(args);
}
When I ran the application and started to chat with the bot, the bot incorrectly replies "I have no answer for that"
Chat
How can I solve this problem?
Add these two permissions to manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
Trying to use the following code to copy a file from one directory to another and rename
String Path3= "/storage/extSDCard/DCIM/Camera/fred.jpg";
File to = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Barr.jpg");
File oldFile = new File (Path3);
oldFile.renameTo(to);
It doesn't appear to copy the file. in this case the path Path3 is on the SDCard but I also need it to copy from one directory to another on the device as well
Basically I'm using the gallery picker to pick an image from somewhere I convert the uri to a path I then need to copy the file from where it is stored to the pictures directory and rename it
Any idea where I'm going wrong?
I solved it from A variety of sources was going about it in the wrong way. This Code Works:
File sourceLocation = new File (Path2);
File targetLocation = new File (Path3 + "/" + imageFileName);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
int actionChoice = 2;
if(actionChoice==1){
if(sourceLocation.renameTo(targetLocation)){
Log.v(TAG, "Move file successful.");
}else{
Log.v(TAG, "Move file failed.");
}
}
else{
if(sourceLocation.exists()){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
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();
}
I'm trying to generate a list of all the files in a particular directory in /data/data/ e.g. /data/data/com.package.ect so that I can zip them. My device is rooted and I've granted Super User to my app. When pass the path to the directory it gets past the if statement, so it recognises that what I'm trying to access is a directory, yet File.list() returns null. I'm assuming I'm still lacking some sort of permission.
/**
* Traverse a directory and get all files,
* and add the file into fileList
* #param node file or directory
*/
public void generateFileList(File node) {
//add file only
if (node.isFile()) {
fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
}
if (node.isDirectory()) {
String[] subNote = node.list();
for (String filename : subNote) {
generateFileList(new File(node, filename));
}
}
}
*EDIT: As requested where generateFileList is called
public void zipDirectory(String outputPath){
byte[] buffer = new byte[1024];
try{
checkStorageDirExists(SDCARD, STORAGE_LOCATION);
generateFileList(new File(path));
FileOutputStream fos = new FileOutputStream(SDCARD + STORAGE_LOCATION + outputPath);
ZipOutputStream zos = new ZipOutputStream(fos);
setZipFileName(path);
Log.i(TAG, "Output to Zip : " + outputPath);
for(String file : this.fileList){
System.out.println("File Added : " + file);
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in =
new FileInputStream(path + "/" + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
zos.close();
Log.i(TAG, "Zip of " + getZipFileName() +" Completed");
}catch(IOException ex){
ex.printStackTrace();
}
I am using a ShareActionProvider to share a vcf file I created.
If I store the file in the external cache, I have absolutely no problems sharing the file, but if I store it in the internal cache, every app I try to share the vCard with says the file is corrupted or unsupported.
I read the file after creating it, and in both cases they are exactly the same.
This code works:
File dir = new File(getExternalCacheDir() + "/contact");
dir.mkdirs();
vcfFile = new File(dir, name.replace(' ', '+') + ".vcf");
However, if I use getCacheDir() instead, I get the problem.
Here's the code for creating the file:
FileWriter fw;
try {
fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
fw.write("VERSION:2.1\r\n");
fw.write("N:" + codedName + "\r\n");
fw.write("FN:" + name + "\r\n");
fw.write("ORG:" + org + "\r\n");
fw.write("TITLE:" + position + "\r\n");
fw.write("TEL;PREF;WORK;VOICE;ENCODING=QUOTED-PRINTABLE:" + phone + "\r\n");
fw.write("TEL;PREF;WORK;FAX;ENCODING=QUOTED-PRINTABLE:" + fax + "\r\n");
fw.write("ADR;WORK;;ENCODING=QUOTED-PRINTABLE:" + codedAddr + "\r\n");
fw.write("EMAIL;INTERNET:" + email + "\r\n");
fw.write("URL;WORK:" + website + "\r\n");
fw.write("PHOTO;TYPE=JPEG;ENCODING=BASE64:" + codedImage + "\r\n");
fw.write("END:VCARD\r\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
And here's the code for the ShareActionProvider:
provider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
if (provider != null) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/vcard");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcfFile));
provider.setShareIntent(intent);
}
Any ideas of what I'm doing wrong?
Any ideas of what I'm doing wrong?
every app I try to share the vCard with says the file is corrupted or unsupported.
According with Using the Internal Storage
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user)...
For this reason, it is advisable to use External Storage
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Code
```
public void sharePublicContact(View view){
String name = "Mickey Mouse";
String org = "Disney Corp.";
String note = "";
File dir = new File(getExternalCacheDir() + "/contact");
dir.mkdirs();
File vcfFile = new File(dir, name.replace(' ', '+') + ".vcf");
FileWriter fw;
try {
fw = new FileWriter(vcfFile);
fw.write("BEGIN:VCARD\r\n");
fw.write("VERSION:3.0\r\n");
fw.write("FN:" + name + "\r\n");
fw.write("ORG:" + org + "\r\n");
fw.write("NOTE:" + note + "\r\n");
fw.write("END:VCARD\r\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/vcard");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(vcfFile));
startActivity(sendIntent);
}
```
I'm trying to get all files list from SD card by Environment.getExternalStorageDirectory() but i get back list from hardware Storage. I tried hardcoded but result is that same. Any idea what could be causing this?
My code
String path = Environment.getExternalStorageDirectory().toString()+"/";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
}
Return
Path: /mnt/sdcard/
Size: 21
FileName:LOST.DIR
FileName:.android_secure
FileName:Music
FileName:Podcasts
But i dont`t have Podcasts etc. in SDcard.
Half answer: Environment.getExternalStorageDirectory() get inside memory storage in some case. If i try String path = "/mnt/external_sd/"; then its work. But in other devices storage is in other dir.
Try this code,
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Save PIP/");
dir.mkdirs();
File file = new File(dir, System.currentTimeMillis() + ".jpg");
// Utils.showAlert("Image Saved to SD Card", "PIP Effect", "Ok", FrameActivity.this);
if (file.exists()) file.delete();
try {
output = new FileOutputStream(file);
bitmap_final.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I wish that it will help you.