How to unzip code on nexus7 - java

How to unzip programming android from asset to /sdcard/, my code in below not success in nexus7, but if it is run in addition to nexus7 will be fine, will be able to extract the data.
To running unzip.
new Thread(new Runnable() {
#Override
public void run() {
UnZip.start();
}
}).start();
private Thread UnZip = new Thread() {
#Override
public void run() {
try {
final int BUFFER = 8192;
ZipInputStream inputStream = new ZipInputStream(getAssets().open("file.zip"));
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
.getNextEntry()) {
String innerFileName = "/sdcard/" + File.separator
+ entry.getName();
File innerFile = new File(innerFileName);
if (entry.isDirectory()) {
innerFile.mkdirs();
} else {
FileOutputStream outputStream = new FileOutputStream(
innerFileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream, BUFFER);
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
bufferedOutputStream.write(data, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
inputStream.closeEntry();
inputStream.close();
} catch (Exception e) {
}
}
};

instead of look for sdcard in this way
String innerFileName = "/sdcard/" + File.separator
+ entry.getName();
use the Environment API
String innerFileName = Environment.getExternalStorageDirectory().toString() + File.separator + entry.getName();
do not forget to add the WRITE_EXTERNAL_STORAGE permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Related

Unable to Unzip file when downloaded from URL, but works when downloaded from FTP

I am trying to download an e-book from URL and unzip it, which further goes for display. While the same unzip logic works perfectly for a FTP download, when it comes to URL, unzipping method does nothing after download.
My book download calling method :
DownloadBook db = new DownloadBook(localFile,"some url",book.key,context,(TaskListener) result -> {
if (result) {
runOnUiThread(() -> pBar.setVisibility(View.VISIBLE));
Runnable t = (Runnable) () -> {
unzip(localFile.getPath(), b.key.replace(".zip",""), b);
isDownloaded = true;
//Deleting downlaoded zip file
System.out.println("zip file deleted - "+localFile.delete());
String urls = localFile.getPath() + "/" + ((b.key).replace(".zip", ""));
System.out.println("URL IS " + urls);
System.out.println("Going for Display");
GlobalVars.title = b.title;
Intent intent = new Intent(My_Library.this, DisplayActivity.class);
startActivity(intent);//
};
t.run();
} else {
runOnUiThread(() ->
{
alert = new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Could not download. Please try again !")
.setCancelable(true)
.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(My_Library.this, My_Library.class);
startActivity(intent);
dialog.cancel();
}
});
alert.create();
alert.show();
}
);
}
});
The zip file download method :
t = new Thread(new Runnable() {
#Override
public void run() {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("some url");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(localFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
System.out.println("Total is "+total);
if(fileLength>0)
{
System.out.println("File length is "+fileLength+" local file length is "+localFile.length());
percent = (int) (total * 100 / fileLength);
System.out.println("FTP_DOWNLOAD bytesTransferred /downloaded -> " + percent);
mProgress.setProgress(percent);
}
output.write(count);
output.flush();
}
mListener.finished(true);
} catch (Exception e) {
e.printStackTrace();
mListener.finished(false);
} finally {
try {
output.flush();
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
The unzip method
public void unzip(String _zipFile, String _targetLocation, Book b) {
pBar.setVisibility(View.VISIBLE);
GlobalVars.path = _targetLocation;
_targetLocation = getApplicationContext().getFilesDir().getPath();
dirChecker(_targetLocation);
try {
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(_zipFile));
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("Unzipping file -> " + ze.getName());
//create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
} else {
File f = new File(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
dirChecker(f.getParent());
long size = f.length();
BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(new File(String.valueOf(f.getAbsoluteFile()))));
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
fout.write(buffer, 0, read);
}
zin.closeEntry();
fout.close();
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
The FTP download class method Unzip works absolutely fine. But as I try to put download from url, it just downloads but not unzips.
You have to change the output buffer writing method.
So instead of, in zip download method
output.write(count);
Use,
output.write(data,0,count);

Android Q Create and save file

I try save a pdf file but on andorid Q I do not see a file. I added all permissions and all permissions are granded also I do this :
public static void saveFile( #NonNull String name, Context context,String base64, Uri imageUri,String path) throws IOException {
Log.e("Path",path);
OutputStream fos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name + ".pdf");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
} else {
String imagesDir = path;
File image = new File(imagesDir, name + ".pdf");
fos = new FileOutputStream(image);
}
byte[] pdfAsBytes = Base64.decode(base64, 0);
assert fos != null;
fos.write(pdfAsBytes);
fos.flush();
fos.close();
}
FileOutputStream os;
String path;
Uri photoURI = null;
photoURI = getUriForFile(context.getApplicationContext(),
BuildConfig.APPLICATION_ID + ".provider", createImageFile(context,cardId));
File dwldsPath = new File(getDefaultTempFilesPath(context) + "/" + cardId +".pdf");
And a probleme is that I do not see a file , a this permissions is added and all is granded :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and I add
android:requestLegacyExternalStorage="true"
if I do this steal I do not have a file butI do not have any exceptions
private static 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 copy file from internal storage to external

I am trying to Copy file from internal memory card to external memory card
By googling i found this answer
try {
InputStream in = new FileInputStream("/storage/sdcard1/bluetooth/file7.zip"); // Memory card path
File myFile = new File("/storage/sdcard/"); //
OutputStream out = new FileOutputStream(myFile);
// 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();
session.showToast("file copied sucessfully");
} catch (FileNotFoundException e) {
showToast(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast(e.getMessage());
e.printStackTrace();
}
its work for internal move to internal or external storage to external
but cross transferring do not work its throws an error Erofs read only file system
Try some thing like this:
new FileAsyncTask().execute(files);
and
// AsyncTask for Background Process
private class FileAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ActivityName.this, "Your Title", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file to the SDCard
public void copyFileToSDCard(String fileFrom){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFrom);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/MyProject", fileFrom));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try this, Replace this line:
File myFile = new File("/storage/sdcard/");
with:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File myFile = cw.getDir("imageDir", Context.MODE_PRIVATE);
Check this link, may be helpfull: click here

Copy file from assets to folder on the sdcard fails

I am using tesseract OCR in my app (Spl!t). When I launch the app from Eclipse to my phone, eng.traineddata is copied into /storage/emulated/0/Pictures/Receipts/tessdata/. But when I installed the app from the market, the eng.traineddata file is not copied into the folder. Is there something wrong with my code?
private File getOutputPhotoFile() {
directory = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Receipts");
dataPath = directory.getAbsolutePath();
if (!directory.exists()) {
directory.mkdirs();
Toast.makeText(Trans_List.this, "Receipts Folder Created", Toast.LENGTH_SHORT).show();
File tessDir = new File(directory, "tessdata");
if (!tessDir.exists()) {
tessDir.mkdirs();
Toast.makeText(Trans_List.this, "Tessdata Folder Created", Toast.LENGTH_SHORT).show();
File trainingData = new File(tessDir, "eng.traineddata");
if(!trainingData.exists())
new CopyLibrary().execute(LANG);
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
return new File(directory.getPath() + File.separator + "Receipt_"
+ timeStamp + ".jpg");
}
private class CopyLibrary extends AsyncTask<String, Void, Void> {
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);
}
#Override
protected Void doInBackground(String... s) {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("Spl!t", "Failed to get asset file list.");
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(dataPath + File.separator
+ "tessdata" + File.separator, LANG
+ ".traineddata");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
Toast.makeText(Trans_List.this, "Tessdata copied", Toast.LENGTH_SHORT).show();
out = null;
} catch (IOException e) {
Log.e(TAG, "Failed to copy asset file");
}
}
return null;
}
}

Store Multiple pcm files in folder on sdcard

I want to save pcm file format file to be store in folder and that folder to be saved on SD card. So far I can save only one file of pcm audio file on SD card. I have tried to store more than one pcm files on SD card but then an error occurred. The error was that I didn't record file. Every time I record some sound, file length remain zero kb.
private void startRecord() {
File path = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MYfolder/");
// File file = new File(path,"myrecording.pcm");
path.mkdirs();
// file = new File(path, "myrecording.pcm");
// // File file = new File(Environment.getExternalStorageDirectory(),
// // "test.pcm");
//
int sampleFreq = 11025; /* (Integer)spFrequency.getSelectedItem(); */
try {
audiofile = File.createTempFile("myrecording", ".pcm", path);
// recorder.setOutputFile(audiofile.getAbsolutePath());
// file.createNewFile();
// File.createTempFile("myrecording", ".pcm", file);
// OutputStream outputStream = new FileOutputStream(file);
OutputStream outputStream = new FileOutputStream(
audiofile.getAbsoluteFile());
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(
bufferedOutputStream);
int minBufferSize = AudioRecord
.getMinBufferSize(sampleFreq, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
sampleFreq, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize);
audioRecord.startRecording();
while (recording) {
int numberOfShort = audioRecord.read(audioData, 0,
minBufferSize);
for (int i = 0; i < numberOfShort; i++) {
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
addRecordingToMediaLibrary();
}
protected void addRecordingToMediaLibrary() {
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/pcm");
values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
ContentResolver contentResolver = getContentResolver();
Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, values);
sendStickyBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
newUri));
Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
}
i have edited my code, i want to save pcm file on sdcard with in specific folder through content resolver. I am get memory leakage error don't known how to solve that.
YOUR_FILE_NAME it should be diffrent every time, use datetime to set file name diffrent
private void startRecordinga() {
AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
//convert short to byte
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void writeAudioDataToFile() {
// Write the output audio in byte
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/Myfolder/"+YOUR_FILE_NAME+".pcm";
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short wirting to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
// stops the recording activity
if (null != recorder) {
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}

Categories

Resources