send image from android java to c# server on pc - java

i'm trying to send image from android to C# server using Socket, but something goes wrong.
package com.example.clientsocket;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView serverMessage;
Thread m_objThreadClient;
Socket clientSocket;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage=(TextView)findViewById(R.id.textView1);
}
public void Start(View view)
{
m_objThreadClient=new Thread(new Runnable()
{
public void run()
{
try
{
clientSocket= new Socket("192.168.88.113",2001);
//ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
File myFile = new File("/storage/sdcard0/Pictures/CameraSample/*.jpg");
InputStream fis = new FileInputStream("/storage/sdcard0/Pictures/CameraSample/*.jpg");
byte [] buffer = new byte[(int)myFile.length()];
fis.read(buffer,0,buffer.length);
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(buffer.length);
outputStream.write(buffer,0,buffer.length);
outputStream.flush();
outputStream.close();
clientSocket.close();
//byte [] buffer = new byte[(int)myFile.length()];
// ...
//fis.read(buffer,0,buffer.length);
//OutputStream os = clientSocket.getOutputStream();
//oos.writeObject("37");
//oos.flush();
//oos.writeObject(buffer);
//os.write(37);
//os.write(buffer);
// <- This one.
/*
int temp = 0 ;
while((temp = fis.read(buffer)) != -1)
{
outputStream.write(buffer, 0, temp);
} */
/*
Message serverMessage= Message.obtain();
ObjectInputStream ois =new ObjectInputStream(clientSocket.getInputStream());
String strMessage = (String)ois.readObject();
serverMessage.obj=strMessage;
mHandler.sendMessage(serverMessage);
oos.close();
ois.close();*/
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
m_objThreadClient.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg)
{
messageDisplay(msg.obj.toString());
}
};
public void messageDisplay(String servermessage)
{
serverMessage.setText(""+servermessage);
}
}
Server gets 60800 as buffer length every single image that I send, and I can't make an image on C# using this array.
I want than to receive char array from server on android.
Am I doing something wrong in the JPG file, because I want to have only one image at the same time in my folder?

This is my sample C# client socket send image to Android Server. In my sending side, I send Image size first and follow by image bytes. Hope it helps.
C# Client
try
{
// IPAddress[] ipAddress = Dns.GetHostAddresses("192.168.173.129");
IPAddress[] ipAddress = Dns.GetHostAddresses("192.168.1.32");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 4800);
string file=#"C:\Users\test\Desktop\send image\test\abc.jpg
{
// Create Socket to send
Socket senderSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
senderSocket.Connect(ipEnd);
//send picture name
// Connect the socket to the remote endpoint. Catch any errors.
FileInfo FileInfo = new FileInfo(file);
byte[] data = new byte[8];
String fInfoStr = FileInfo.Length.ToString();
while (fInfoStr.Length < 8)
{
fInfoStr = "0" + fInfoStr;
}
byte[] countBuf = Encoding.ASCII.GetBytes(fInfoStr);
byte[] fBuffer = new byte[FileInfo.Length];
//FileStream
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
//Read byte from image
fs.Read(fBuffer, 0, fBuffer.Length);
fs.Flush();
fs.Close();
senderSocket.Send(fBuffer, 0, fBuffer.Length, SocketFlags.None);
senderSocket.Close();
lblTestMsg.Visible = true;
lblErrorMsg.Visible = false;
lblTestMsg.Text = "File Sent Successfully";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Android Server
Socket socket = serverSocket.accept();
InputStream iStream = socket.getInputStream(); ;
String currentDateandTime = sdf.format(new Date());
// int filenamelen =iStream.read();
//image Name
byte[] countBuf = new byte[8];
// byte[] imageNameByte = new byte[7];
iStream.read(countBuf);
//iStream.read(imageNameByte,0,7);
readTxt = new String(countBuf);
// imageName= new String(imageNameByte);
int size = Integer.parseInt(readTxt);
//Send byte array
senderSocket.Send(countBuf, 0, data.Length, SocketFlags.None);new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName).mkdirs();
Log.e("TCP", "Create Drkt");
//Create Image(File)
new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName, imageName + ".jpg").createNewFile();
Log.e("TCP", "Create Img");
try {
FileOutputStream fOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName + File.separator + imageName + ".jpg");
BufferedOutputStream BufOutputStream = new BufferedOutputStream(fOutputStream);
byte[] aByte = new byte[size];
int byteRead;
// int bytesRead = iStream.read(aByte);
//Read from server
while ((byteRead = iStream.read(aByte)) > 0) {
Log.e("TCP", "Save to file");//Write to file
BufOutputStream.write(aByte, 0, byteRead);
}
publishProgress();
notifyID++;
// String imageUri =Environment.getExternalStorageDirectory() + File.separator + "myDirectory" + File.separator + readTxt + File.separator+currentDateandTime+".jpg";
BufOutputStream.flush();
BufOutputStream.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}

You have a mistake in this code:
byte [] buffer = new byte[(int)myFile.length()];
fis.read(buffer,0,buffer.length);
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(buffer.length); // You are changing the image here...
outputStream.write(buffer,0,buffer.length);
You are sending wrong data on the Socket, and you may run on out of memory if image is to big. Also you are converting myFile.length() to int. There is a reason for files length to be long. It allow very large files to be scanned. May be it doesn't meter in your case but I suggest not doing this.
It should be some thing like this:
byte [] buffer = new byte[1048];
OutputStream outputStream = clientSocket.getOutputStream();
int numberOfBytesBeenRead = fis.read(buffer,0,buffer.length);
while(numberOfBytesBeenRead != -1){
outputStream.write(buffer,0,numberOfBytesBeenRead);
numberOfBytesBeenRead = fis.read(buffer,0,buffer.length);
}

Related

client.getInputStream returns null

I am trying to use the WifiDirect demo api to send a recorded audio to another android device but input stream from the socket always returns null.
Any help is much appreciated.
Here are portion of the code
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory(), File.separator + "SuDAB/received/"
+ "sudab-" + System.currentTimeMillis()
+ ".3gp");
File dirs = new File(f.getParent());
if (!dirs.exists()) {
dirs.mkdirs();
}
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
and
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime = System.currentTimeMillis();
if (inputStream == null) {
return false;
}
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime = System.currentTimeMillis() - startTime;
Log.v(WiFiDirectActivity.TAG, "Time taken to transfer all bytes is : " + endTime);
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
this is how i pass the file to be sent to the FileTransferService
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Allow user to pick an image from Gallery or other
// registered apps
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + lastFile);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + lastFile);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
Log.d(WiFiDirectActivity.TAG, "File transfer service created...");
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
});
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
should be
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, "file://"+lastFile);
instead.

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

UDP with sequence numbers

I am trying to implement a Reliable UDP protocol for a class assignment in Java. I have managed to add the acknowledgments to every datagram packet that is received, but I am having trouble implementing Sequence Numbers in the datagram packets that I am sending.
Can anyone suggest an easy method to implement this?
#EJP I have tried implementing what you just suggested. This is my code till now (its still very raw - i was using hit and try method to implement it)
Server side
public class TestServer extends Activity {
private DatagramSocket serverSocket;
Thread serverThread = null;
byte[] incomingData;
byte[] outgoingData;
//int numBytesRead = 0;
int ackSent = 0;
int numPackRecv = 0;
int BUF_SIZE = 1024;
String msg = "ACK";
BufferedInputStream data=null;
BufferedOutputStream out =null;
public static final int SERVERPORT = 6000;
String outputFile = "/sdcard/Movies/asddcopy.mp4";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_server);
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (Exception e) {
Log.d("SERVER", "Inside onStop()");
Log.d("SERVER", Log.getStackTraceString(e));
}
}
class ServerThread implements Runnable {
#SuppressLint("NewApi")
public void run() {
try {
serverSocket = new DatagramSocket(SERVERPORT);
incomingData = new byte[BUF_SIZE];
//outgoingData = new byte[512];
outgoingData = msg.getBytes();
long startRxPackets = TrafficStats.getUidRxPackets(Process.myUid());
long startTime = System.nanoTime();
out = new BufferedOutputStream(new FileOutputStream(outputFile, true));
while (!Thread.currentThread().isInterrupted()) {
//serverSocket.setSoTimeout(5000);
while (true) {
try{
//DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
DatagramPacket incomingPacket = new DatagramPacket(incomingData, BUF_SIZE);
serverSocket.receive(incomingPacket);
byte[] data = incomingPacket.getData();
//out.write(data,0,incomingPacket.getLength());
//String msg = new String(incomingPacket.getData());
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
if (is == null) {
is = new ObjectInputStream(in);
}
Message msg = (Message) is.readObject();
System.out.println(msg.getSeqNo());
/*if ("END".equals(msg.substring(0, 3).trim())) {
Log.d("SERVER", "Inside END condition");
break;
}*/
out.write(msg.getData(),0,msg.getData().length);
numPackRecv += 1;
Log.d("SERVER", "Packet Received: " + numPackRecv);
InetAddress client = incomingPacket.getAddress();
int client_port = incomingPacket.getPort();
DatagramPacket outgoingPacket = new DatagramPacket(outgoingData, outgoingData.length, client, client_port);
serverSocket.send(outgoingPacket);
ackSent += 1;
//Log.d("SERVER","Packet Received: " + numPackRecv + " :: " + "Ack Sent: " + ackSent);
}catch(Exception e) {
Log.d("SERVER", "Inside run() ex1");
Log.d("SERVER", Log.getStackTraceString(e));
break;
}
}
out.close();
serverSocket.disconnect();
serverSocket.close();
Log.d("SERVER", "Transfer Complete");
Log.d("SERVER", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("SERVER", "Total Packets Received = " + Long.toString(TrafficStats.getUidRxPackets(Process.myUid()) - startRxPackets));
Log.d("SERVER", "Packets Received from Socket = " + numPackRecv);
break;
}
out.close();
serverSocket.disconnect();
serverSocket.close();
/* Log.d("SERVER", "Transfer Complete");
Log.d("SERVER", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("SERVER", "Total Packets Received = " + Long.toString(TrafficStats.getUidRxPackets(Process.myUid()) - startRxPackets));
Log.d("SERVER", "Packets Received from Socket = " + numPackRecv);*/
}catch (Exception e) {
Log.d("SERVER", "Inside run() ex2");
Log.d("SERVER", Log.getStackTraceString(e));
serverSocket.disconnect();
serverSocket.close();
}
}
}
This is the Client side
public class TestClient extends Activity { private DatagramSocket clientSocket;
byte[] incomingData;
int BUF_SIZE = 500;
int numBytesRead = 0;
int numPackSent = 0;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "10.0.0.22";
String inFile = "/sdcard/Movies/asdd.mp4";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_client);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
new workInProgress().execute("");
}
private class workInProgress extends AsyncTask<Object, Object, Object> {
#SuppressLint("NewApi")
#Override
protected Object doInBackground(Object... params) {
try {
Log.d("CLIENT", "Sending a file to the server...");
BufferedInputStream inputBuf = new BufferedInputStream(new FileInputStream(inFile));
//byte[] fileBytes = new byte[(int) inFile.length()];
byte[] fileBytes = new byte[BUF_SIZE];
incomingData = new byte[BUF_SIZE];
double numPktToSend = Math.ceil(inFile.length()*1.0/BUF_SIZE);
//Log.d("CLIENT", "Total packets to be sent = " + numPktToSend);
int sleepCycle = 1;
long sysPackSent = 0;
//long startTxPackets = TrafficStats.getTotalTxPackets();
long startTxPackets = TrafficStats.getUidTxPackets(Process.myUid());
Log.d("CLIENT", "startTxPacks: " + startTxPackets);
long packDrops = 0;
long startTime = System.nanoTime();
long count=0;
long ackRec=0;
int seqNo = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outStream);
while((numBytesRead = inputBuf.read(fileBytes)) != -1) {
//DatagramPacket packet = new DatagramPacket(fileBytes, fileBytes.length);
if (os == null) {
os = new ObjectOutputStream(outStream);
}
Message msg = new Message(++seqNo, fileBytes, false);
os.writeObject(msg);
os.flush();
os.reset();
byte[] data = outStream.toByteArray();
DatagramPacket packet = new DatagramPacket(data, data.length);
clientSocket.send(packet);
numPackSent += 1;
//Log.d("CLIENT", "No of packets sent = " + numPackSent);
sysPackSent = TrafficStats.getUidTxPackets(Process.myUid()) - startTxPackets;
try{
clientSocket.setSoTimeout(5000);
packet = new DatagramPacket(incomingData, incomingData.length);
clientSocket.receive(packet);
String recAck = new String(packet.getData());
ackRec++;
}
catch(Exception e) {
//Log.d("CLIENT", Log.getStackTraceString(e));
}
packDrops = numPackSent - ackRec;
if (packDrops > count) {
sleepCycle = Math.min(16, sleepCycle * 2);
count = packDrops;
Log.d("CLIENT",String.valueOf(sleepCycle) + " :: " + numPackSent);
} else {
sleepCycle = Math.max(sleepCycle - 1, 1);
}
Thread.sleep(sleepCycle);
}
if (numBytesRead == -1) {
fileBytes = "END".getBytes();
Log.d("CLIENT", "Sending END Packet");
clientSocket.send(new DatagramPacket(fileBytes, fileBytes.length));
}
Log.d("CLIENT", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("CLIENT", "Total Packets Transmitted = " + Long.toString(sysPackSent));
Log.d("CLIENT", "No of packets dropped = " + String.valueOf(packDrops));
Log.d("CLIENT", "Packets Pushed to Socket = " + numPackSent);
Log.d("CLIENT", "Number of Acknoledgments received " +ackRec);
inputBuf.close();
os.close();
outStream.close();
clientSocket.disconnect();
clientSocket.close();
Log.d("CLIENT", "Sending file.. Complete!!!");
} catch (Exception e) {
Log.d("CLIENT", Log.getStackTraceString(e));
clientSocket.disconnect();
clientSocket.close();
}
return null;
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
clientSocket = new DatagramSocket();
clientSocket.connect(serverAddr, SERVERPORT);
Log.d("CLIENT", "Connection Successful");
} catch (UnknownHostException e1) {
Log.d("CLIENT", "Inside run() UnknownHostEx");
Log.d("CLIENT", Log.getStackTraceString(e1));
} catch (IOException e1) {
Log.d("CLIENT", "Inside run() IOEx");
Log.d("CLIENT", Log.getStackTraceString(e1));
}
}
}
I am getting a few errors at the Server side:
I am receiving the same sequence number for each packet (i.e. 1)
I am not sure about the buffer size for the incoming packet, as I am using 500 bytes at Client side and 1024 at the Sever. And if I take 500 bytes in both the codes I get a End of File exception.
I would really appreciate if you could suggest better ways to implement the same thing!
Thanks :)
Thanks!
Create a ByteArrayOutputStream.
Wrap it in a DataOutputStream
Use DataOutputStream.writeInt() to write the sequence number.
Use write() to write the data.
Construct the DatagramPacket from the byte array returned by the ByteArrayOutputStream.
At the receiver, do exactly the reverse, using the complementary classes and methods in each case. What those are is left as an exercise for the reader.
The simplest method would probably be to a look at the TCP protocol, and stick all the TCP headers into the start of each of your UDP packets.

copying to another apps unprotected storage Android

I'm trying to wirte files to the internal storage actually to an other apps unprotected storage the code I'm using works it just doesn't work when I want to copy to /android/data/com.some.app can this be done or do I have to make the app use root access
Thanks
public class tools extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tools);
}
public void installflat(View view)
{ Toast.makeText(tools.this, "This could take a long time", Toast.LENGTH_LONG).show();
File direct = new File(Environment.getExternalStorageDirectory() + "/android" + "/data" + "/com.some.app" +"/");
if (!direct.exists())
{
if (direct.mkdir())
{ //directory is created;
}}
installflat_pt2();
Toast.makeText(tools.this, "try it now", Toast.LENGTH_LONG).show();
}
private void installflat_pt2()
{
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("tools");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for (String filename : files)
{
System.out.println("File name => " + filename);
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open("tools/" + filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/android" + "/data" + "/com.some.app" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
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);
}
}
}

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