Issue In Zipping Pcap Files - java

I am generating pcap files and need to zip it. Currently i am able to generate and store the pcap file in local storage.
for zipping i am using below code:
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
byte[] buffer = new byte[1024];
try {
zipFilePath = urls[0];
FileOutputStream fos = new FileOutputStream(zipFilePath + ".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(urls[1]);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(zipFilePath);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
//remember close it
zos.close();
return zipFilePath + ".zip";
} catch (IOException ex) {
ex.printStackTrace();
return "";
}
}
I am getting file not found exception at FileOutputStream fos = new FileOutputStream(zipFilePath + ".zip");

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 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;
}
}

android: FileOutputStream Doesn't work

I try to make TCP-Sock program, and this is simple file recv program.
and now, i get some problem.
i think my client program's FileOutputStream class doesn't work.
below code is what i've made.
package kr.ac.cbnu.incping.tcp_cloud;
public class DownActivity extends Activity {
public static int contentNum;
public static String body=new String();
public static String fName=new String();
public static int fSize;
public static synchronized String getFilePath(String userID, String fName)
{
String sdcard = Environment.getExternalStorageState();
File file = null;
if ( !sdcard.equals(Environment.MEDIA_MOUNTED))
{
// SDcard isn't mount
file = Environment.getRootDirectory();
}
else
{
// SDcard is mount
file = Environment.getExternalStorageDirectory();
}
String dir = file.getAbsolutePath() + String.format("/tcp_cloud/%s",userID);
String path = file.getAbsolutePath() + String.format("/tcp_cloud/%s/%s",userID,fName);
file = new File(dir);
if ( !file.exists() )
{
// Make directory if dir doesn't exist
file.mkdirs();
}
// return File Path;
return path;
}
public void connect()
{
try{
Socket socket=new Socket(MainActivity.servIP, MainActivity.servPort);
DataOutputStream dos;
DataInputStream dis;
dis=new DataInputStream(socket.getInputStream());
dos=new DataOutputStream(socket.getOutputStream());
byte[]flag=new byte[3];
byte[]num=new byte[1];
byte[]uID=new byte[17];
String path=new String();
path=getFilePath(LoginActivity.usrName,fName);
File f=new File(path);
flag="05".getBytes("EUC_KR");
num=Integer.toHexString(contentNum).getBytes("EUC_KR");
uID=LoginActivity.usrName.getBytes("EUC_KR");
dos.write(flag);
dos.flush();
dos.write(num);
dos.flush();
dos.write(uID);
dos.flush();
FileOutputStream fos=new FileOutputStream(f);
Toast.makeText(getApplicationContext(),path,Toast.LENGTH_LONG).show();
BufferedOutputStream bos=new BufferedOutputStream(fos);
dos=new DataOutputStream(bos);
int len;
int size = 512;
byte[] data = new byte[size];
while ((len = dis.read(data,0,size))!=-1)
{
dos.write(data);
}
dos.flush();
Toast.makeText(getApplicationContext(),path+" saved",Toast.LENGTH_LONG).show();
dos.close();
bos.close();
fos.close();
dos.close();
dis.close();
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_down);
String title=new String();
if(contentNum==0)
title=LoginActivity.title1;
else if(contentNum==1)
title=LoginActivity.title2;
else if(contentNum==2)
title=LoginActivity.title3;
else if(contentNum==3)
title=LoginActivity.title4;
else if(contentNum==4)
title=LoginActivity.title5;
TextView bodytit=(TextView) findViewById(R.id.bodyTitle);
TextView bodydat=(TextView) findViewById(R.id.bodyBody);
Button filedat=(Button) findViewById(R.id.filename);
bodytit.setText(title);
bodydat.setText(body);
filedat.setText(fName+"(size: "+fSize+")");
filedat.setOnClickListener(new OnClickListener(){
public void onClick(View v){
connect();
}
});
}}
and this code is troubled code
FileOutputStream fos=new FileOutputStream(f);
Toast.makeText(getApplicationContext(),path,Toast.LENGTH_LONG).show();
BufferedOutputStream bos=new BufferedOutputStream(fos);
dos=new DataOutputStream(bos);
toast message is just prob message. when placed toast above of the FOS, toast working well.
but toast isn't working in that position
i can't solve this problem. please, somebody help me..T.T
*i'm not english language area's person. so my english isn't nice sentence. i'm sorry about that;)
In my case FileOutputStream and OutputStreamWriter is not works.
So I was changed File classes to this.
FileWriter fileOut = new FileWriter(fileFullPath, false);
String jsonString = new Gson().toJson(json);
fileOut.write(jsonString);
fileOut.close();

How to unzip code on nexus7

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>

Categories

Resources