I have a method that tries to extract m3u files, but it doesn't work at api level 29. I get the following error on the Logcat screen:
2019-10-03 20:46:53.165 32591-417/? E/Google: java.io.IOException: Cleartext HTTP traffic to mysite.tk not permitted
My Method:
#SuppressLint("StaticFieldLeak")
class _loadFile extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(String... strings) {
try { //new FileInputStream (new File(name)
is = new FileInputStream(new File(strings[0])); // if u r trying to open file from asstes InputStream is = getassets.open(); InputStream
M3UPlaylist playlist = parser.parseFile(is);
mAdapter.update(playlist.getPlaylistItems());
return true;
} catch (Exception e) {
Log.d("Google", "_loadFile: " + e.toString());
return false;
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
spinner.setVisibility(View.GONE);
}
}
EDİT:
I gave ClearText permission, but a new error appeared.
Google: _loadFile: java.io.FileNotFoundException: /storage/emulated/0/Netuptv/data.m3u: open failed: ENOENT (No such file or directory)
EDİT:
My file path. I think the problem is here. But I don't have the information to solve it.
static final File DEFA = Environment.getExternalStorageDirectory();
public static final File dir = new File(DEFA.getPath() + "/Netuptv");
static final File filepath = new File(dir.getPath() + "/data.m3u");
Please check if you added this line android:usesCleartextTraffic="true" to your Manifest.
Since the file access API is deprecated on Android Q, I highly recommend to you to read this article by CommaneWare , as mention on this article, try to use android:requestLegacyExternalStorage="true" to avoid the file access issues
Try the following :
String fileName = "data.m3u";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
+ "/Netuptv");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File file = new File(storageDir,fileName);
filepath = file.getAbsolutePath();
}
With Android 10 (api level 29) file access is deprecated, it's called scoped storage.
A quick but not permanent fix for testing on Android 11:
Adding android:requestLegacyExternalStorage="true"
and changing
compileSdkVersion 29
targetSdkVersion 29
both to 29 in build.gradle
Related
I want to implement this functionality;
A Button when pressed will install .xapk file from local storage with the following path.
String _apkFilePath = '/storage/emulated/0/Download/filename.xapk';
Duplicate of: I am making an .XAPK installer application in flutter. with open_file package I can open normal .apk installation dialogue but how can I install .XAPK
If you're still trying to install an .xapk file, I'm sharing a piece of code that helped me. I'm using the packages:
archive (for all the extraction as zip logic)
device_apps (to open the Settings app in case you don't have the required permissions)
open_filex (to open the apk file with the Android intent)
package_archive_info (to get the information from the .apk package)
path_provider (to get Directories and paths)
permission_handler (to ask for permissions to install)
and file_picker since I initiate the method with a picked file using that package.
abstract class XapkInstaller {
static install({required PlatformFile file}) async {
late List<FileSystemEntity> allFiles, apkFiles;
late PackageArchiveInfo appInfo;
late String appPackageName;
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
String appName = file.path.toString().split("/").last.replaceAll(".apklis", "");
String zipFilePath = "${tempDir.path.replaceAll('/$appName.apklis', '')}/$appName.zip";
// this function convert xapk in zip file and moves in appname_zip directory
_moveFile(File(file.path.toString()), zipFilePath);
final bytes = File(zipFilePath).readAsBytesSync();
final archive = ZipDecoder().decodeBytes(bytes);
// Extract the contents of the Zip archive to disk app cache.
for (final file in archive) {
final String filename = file.name;
if (file.isFile) {
final data = file.content as List<int>;
File("${tempDir.path}/$appName/$filename")
..createSync(recursive: true)
..writeAsBytesSync(data);
} else {
Directory(tempPath).create(recursive: true);
}
}
final Directory myDir = Directory("${tempDir.path}/$appName");
allFiles = myDir.listSync(recursive: true, followLinks: true);
apkFiles = allFiles.where((element) => element.path.endsWith('.apk')).toList();
for (int x = 0; x < apkFiles.length; x++) {
final String filePath = apkFiles[x].path;
try {
appInfo = await PackageArchiveInfo.fromPath(filePath);
appPackageName = appInfo.packageName;
} catch (e) {
appInfo = PackageArchiveInfo(appName: "", packageName: "", version: "", buildNumber: "");
}
if (appInfo.appName.isNotEmpty) {
try {
// moving obb file to android/obb folder
_moveObbToAndroidDir(allFiles, appPackageName);
// showing popup to install app
if (await Permission.requestInstallPackages.request().isGranted) {
await OpenFilex.open(filePath);
} else {
DeviceApps.openAppSettings(appInfo.packageName);
}
} catch (e) {
//catch error in installing
}
}
}
// clearing cache file after installing xapk
Future.delayed(const Duration(seconds: 180), () {
tempDir.deleteSync(recursive: true);
tempDir.create();
});
}
static _moveObbToAndroidDir(List<FileSystemEntity> allFiles, String appPackageName) async {
for (int x = 0; x < allFiles.length; x++) {
final fileExtension = allFiles[x].path.split("/").last.split(".").last;
if (fileExtension == "obb") {
String filepath = allFiles[x].path;
String obbFileName = filepath.split("/").last.split(".").first;
String obbDirPath = "/Android/obb/$appPackageName";
// creating the directory inside android/obb folder to place obb files
if (!Directory(obbDirPath).existsSync()) {
Directory(obbDirPath).createSync();
}
// rename path should also contains filename i.e. whole path with filename and extension
final String renamePath = "$obbDirPath/$obbFileName.obb";
try {
// syncronus copying
File(filepath).copySync(renamePath);
} on FileSystemException {
// in case of exception copying asyncronushly
await File(filepath).copy(renamePath);
}
}
}
}
static Future<File> _moveFile(File sourceFile, String newPath) async {
try {
// prefer using rename as it is probably faster
return await sourceFile.rename(newPath);
} on FileSystemException catch (e) {
// if rename fails, copy the source file and then delete it
final newFile = await sourceFile.copy(newPath);
await sourceFile.delete();
return newFile;
}
}
}
I've tried it and it works, so remember to update the permissions on the AndroidManifest file and you're all set.
(to make things clearer :) I am using WebView. The idea is that users can visit any page and download any file, the idea is to support as many basic features as i can to get closer feel to built in web browser.
As the title says, i am trying to make my app download files and open them once theyre downloaded. There are some bullet points i want to mention :
user should be able to download any kind of file (i guess its called mimeType), as they would in they default internet browser app
since users download items from webview, it would only make sense if downloads would appear in downloads folder
would be awesome if every users device could decide on itself which app to use to open downloaded file, but, for example, my samsung s9 asks which app to use, thats not a bad option either
i ran across some problems like sucessful download, but the file was empty/corrupted, the downlaoded file was missing in file browser even if app told me that the download is completed
So i have been on not 2nd, not 3rd but even 5th page of google search results, so ive seen a lot, these are couple versions of my code so far, every single one of them are not working as i expected them in my dreams.
Just to be clear, the code you are about to see is under webview setDownloadListener(new DownloadListener() ...
So my latest version, without file opening after download :
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
//used to call a class to in previous code version to make some downloads
//new DownloadTask(webview_base.this, url, mimeType);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf('/')));
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});
the problem with ^ this version was that i was able to download files, but it downlaoded pages HTML instead of actual pdf or whatever i was aiming for, thats weird.
previous version was a bit smoother, i was able to download files, and i used a dialog to offer to open a file. Everything worked fine, but documents were empty/corrupted and i got offered to open them with weird apps, for example, once i got asked to open pdf with my smartwatch app, but that mustve gone away since i edited a code time by time. The problem i landed here was that even after couple of ctrl+z i wasnt able to get my app back on feets - i was stuck at download screen and logcat shout at me that it couldnt fine a download directory. at that point i got mad and started the version you can see above. Anyway, here is the whole class :
package com.example.viaapp_v2;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import androidx.core.content.FileProvider;
public class DownloadTask extends FileProvider {
private static final String TAG = "Download Task";
private Context context;
String mimeType;
private String downloadUrl = "", downloadFileName = "";
private ProgressDialog progressDialog;
public DownloadTask() {
//required empty constructor
}
public DownloadTask(Context context, String downloadUrl, String mime) {
this.context = context;
this.downloadUrl = downloadUrl;
this.mimeType = mime;
//Create file name by picking download file name from URL
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'));
//Start Downloading Task
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
File apkStorage = null;
File outputFile = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Downloading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
progressDialog.dismiss();
final ContextThemeWrapper ctw = new ContextThemeWrapper( context, R.style.Theme_AppCompat_Light_Dialog);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
alertDialogBuilder.setTitle("Document ");
alertDialogBuilder.setMessage(downloadFileName+" Downloaded Successfully ");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialogBuilder.setNegativeButton("Open file",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
+ downloadFileName);//name here is the name of any string you want to pass to the method
if (!file.isDirectory())
file.mkdir();
Intent testIntent = new Intent();
testIntent.setType(mimeType);
testIntent.setAction(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
testIntent.setDataAndType(uri, mimeType);
ctw.startActivity(testIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
alertDialogBuilder.show();
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed");
}
} catch (Exception e) {
e.printStackTrace();
//Change button text if exception occurs
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
}
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(downloadUrl);//Create Download URl
HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
c.connect();//connect the URL Connection
//If Connection response is not OK then show Logs
if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
+ " " + c.getResponseMessage());
}
//Get File if SD card is present
if (new CheckForSDCard().isSDCardPresent()) {
apkStorage = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
} else
Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
//If File is not present create directory
if (!apkStorage.exists()) {
apkStorage.mkdir();
Log.e(TAG, "Directory Created.");
}
outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
//Create New File if not present
if (!outputFile.exists()) {
outputFile.createNewFile();
Log.e(TAG, "File Created");
}
FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
InputStream is = c.getInputStream();//Get InputStream for connection
byte[] buffer = new byte[1024];//Set buffer type
int len1 = 0;//init length
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);//Write new file
}
//Close all connection after doing task
fos.close();
is.close();
} catch (Exception e) {
//Read exception if something went wrong
e.printStackTrace();
outputFile = null;
Log.e(TAG, "Download Error Exception " + e.getMessage());
}
return null;
}
}
private class CheckForSDCard {
//Check If SD Card is present or not method
boolean isSDCardPresent() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
}
}
Looking for my manifest file ? Well here it goes .. ive put in some support for file upload, file download, internet acces, ect
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.CAMERA"/>
i even tried to put some provider stuff in application
<provider
android:name=".DownloadTask"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
But deep inside i had no idea what to put in provider path file
<paths><external-path name="external_files" path="."/></paths>
Sorry that this text is so long. Im just desperate and almost done with my project, but i have to seek for help somewhere to keep going. I hope ive explained my problem enough and provided enough code, would be happy to know which code is better / more possible ( make a class or write everything down right under listener ).
--- EDIT ---
So.. i tried to run my old version of code, which is that long block of code above, class file "DownloadTask.java", which is called by constructor, passing utl, mimetype and context. You can see the line commented in the first block of code in this post, 3rd line. Here is what happened : i visited a page, clicked on a link to download pdf file, but then i got stuck on dialog that shows "downloading.." while logcat said this :
D/ViewRootImpl#19478bd[webview_base]: MSG_RESIZED: frame=Rect(18, 617 - 701, 821) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl#c47c382[webview_base]: Relayout returned: old=[0,0][720,1480] new=[0,0][720,1480] result=0x1 surface={valid=true 484837122048} changed=false
I/ample.viaapp_v: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Download/Datu%20p%C4%81rraides%20t%C4%ABkli-III_LV.pdf (Is a directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:308)
at java.io.FileOutputStream.<init>(FileOutputStream.java:238)
at java.io.FileOutputStream.<init>(FileOutputStream.java:180)
at com.example.viaapp_v2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:173)
at com.example.viaapp_v2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:54)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
E/Download Task: Download Error Exception /storage/emulated/0/Download/Datu%20p%C4%81rraides%20t%C4%ABkli-III_LV.pdf (Is a directory)
E/Download Task: Download Failed
D/ViewRootImpl#19478bd[webview_base]: MSG_WINDOW_FOCUS_CHANGED 1 1
And yes, as you can see, the file name contais accented letters, thats why its so weird, 99% of users which are willing to use the app, will work around content which uses accented letters so im wondering mayeb i should replace filenames without all these letters like "āēīģčķ" to "aeigck".
As i am doing a backporting task i need to get an application from Android 9 to Android 5.1 to work.
It contains a lot of functionalities related to files like Exporting and importing of Json files and creating directories.
Is there an alternative to the File functionalities found in Java 8, or a way to get them in Java 7 or some library that backports those as i just cannot find a solution to this.
Thanks!
Here are is a method as an example of what i would like to backport.
public static void exportLogcats(final Context context, final List<BootEvent> events,
final String outputFolder) throws IOException {
if (events == null) {
return;
}
final String sourceFolder =
new File(context.getFilesDir(), LOGCAT_FOLDER).getAbsolutePath();
final Path outputPath;
outputPath = Paths.get(outputFolder);
deleteDirectory(outputPath);
Files.createDirectories(outputPath);
for (BootEvent event : events) {
final String filename = event.getLogcatFilename();
try {
final Path source;
source = Paths.get(sourceFolder, filename);
final Path destination = Paths.get(outputFolder, filename);
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException | NullPointerException e) {
Log.e(LOG_TAG, "Could not copy file " + filename, e);
}
}
}
The problem is that calls like
.get on Paths, .createDirectories or .copy on Files does not work on API level 22
I want to read from txt file and send to TextView. My method works on Java Project I read and I see System.out.print but the same method doesnt work in MainActivity. How can I fixed.Thanks
MainActivity
public class MainActivity extends Activity {
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.textView1);
Parsing p =new Parsing();
try {
String gelen=p.readTxt();
txt.setText(gelen);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Parsing:
public class Parsing {
public String readTxt() throws FileNotFoundException
{
File file = new File("C:\\Users\\John\\Desktop\\try.txt");
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
}
I'm working it but I see just TextView.
you cannot specify the computer directory files to the android file path location to read lines in it.
just put the file into your android project folder like assests and change the
path and then try.
How can I read a text file in Android?
I don't mean to be rude but try to search first. This question with similar problem was already asked.
I hope this link will help you.
Cheers
For file on sdcard ("sdcard\myfolder\1.txt") please use:
File file = new File(Environment.getExternalStorageDirectory(), "myfolder\1.txt");
Also dont forget:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You must put the file in the asset folder of your project.
Then to access it you can do something like
BufferedReader reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
for more details read my answer here :
read file from assets
First of all Android Application Project is different from Java Project.
You can not use File file = new File("C:\\Users\\John\\Desktop\\try.txt"); in android.
Place your text file in the /assets directory under the Android project. Use AssetManager class to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
If you are going to access file from memory card, Then use inputsteram is in your program. Also you need the following permission to read the text file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am trying to unzip a zipfile with password protection. I know there is a java library named "zip4j" that could help me. But I am failing to open the zip4j website to see the tutorial.
I had download zip4j library with another mirror but I don't know how to use it. Is there anyone that could paste example code for using zip4j unzip password protection zip file?
zip4j website
thanks so much!
Try the following and make sure you are using the most recent Zip4j library (1.3.1):
String source = "folder/source.zip";
String destination = "folder/source/";
String password = "password";
try {
ZipFile zipFile = new ZipFile(source);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destination);
} catch (ZipException e) {
e.printStackTrace();
}
Here we have a file game.zip in Downloads folder in android phone and we are extracting it with the password given below:
String unzipFileAddress = Environment.DIRECTORY_DOWNLOADS "/Game.zip";
String filePassword = "2222"; // password of the file
String destinationAddress = Environment.DIRECTORY_DOWNLOADS + "/Game";
ZipFile zipFile = new ZipFile(unzipFileAddress, filePassword.toCharArray());
try {
zipFile.extractAll(destinationAddress);
} catch (Exception e) {
// if crashes print the message or Toast
}
Add in dependencies in build Gradle (app level) before doing it
dependencies{
implementation 'net.lingala.zip4j:zip4j:2.6.4'
} // for lastest version check the link below
Make sure you have storage permission, these silly mistakes can take your valuable time
// Add in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Make sure your zip file is not a corrupt file by extracting it manually.
If you want to do some complex work with compression, you should take help from here: https://github.com/srikanth-lingala/zip4j
Full Implementation to Zip/Unzip a Folder/File with zip4j
Add this dependency to your build manager. Or, download the latest JAR file from here and add it to your project build path. The class bellow can compress and extract any file or folder with or without password protection-
import java.io.File;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import net.lingala.zip4j.core.ZipFile;
public class Compressor {
public static void zip (String targetPath, String destinationFilePath, String password) {
try {
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if (password.length() > 0) {
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}
ZipFile zipFile = new ZipFile(destinationFilePath);
File targetFile = new File(targetPath);
if (targetFile.isFile()) {
zipFile.addFile(targetFile, parameters);
} else if (targetFile.isDirectory()) {
zipFile.addFolder(targetFile, parameters);
} else {
//neither file nor directory; can be symlink, shortcut, socket, etc.
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password) {
try {
ZipFile zipFile = new ZipFile(targetZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destinationFolderPath);
} catch (Exception e) {
e.printStackTrace();
}
}
/**/ /// for test
public static void main(String[] args) {
String targetPath = "target\\file\\or\\folder\\path";
String zipFilePath = "zip\\file\\Path";
String unzippedFolderPath = "destination\\folder\\path";
String password = "your_password"; // keep it EMPTY<""> for applying no password protection
Compressor.zip(targetPath, zipFilePath, password);
Compressor.unzip(zipFilePath, unzippedFolderPath, password);
}/**/
}
For more detailed usage, see here.
If you are working on android, then please make sure that you have added storage permission in the manifest file.