PC to Android File Transfer through Sockets - android

How to transfer a file(unknown extension ie maybe a pdf/word/jpeg) from PC to Android Phone using Socket Programming. The Android Phone should be able to detect the type of file transfer and should be able to open it thereafter. Also the file should go into a specific folder named after app name in External storage.
I have tried following solution. However in this case, when I select the file to be transferred, the file transferred at Android side is of arbitrary size and not of the same size as of file selected, it is of some random size. Also the file transferred cannot be opened as it does not have a fixed extension.
Any help would be appreciated.
Android code(To receive file)
package minor.subham.com.pccontrol;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.net.*;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class getFile extends ActionBarActivity {
ImageView getFile;
public final static int SOCKET_PORT = Constants.SERVER_PORT; // you may change this
public final static String SERVER = Constants.SERVER_IP; // localhost
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_file);
getFile = (ImageView) findViewById(R.id.getFile);
getFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
final File file;
file = new File(Environment.getExternalStorageDirectory(), "PcControl");
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
// fos = new FileOutputStream(FILE_TO_RECEIVED);
try {
fos = new FileOutputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
fos.write(mybytearray);
fos.close();
System.out.println("File "
+ " downloaded (" + current + " bytes read)");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null) try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (sock != null) try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
thread.start();
}
});
}
}
And Her is the Java Code to send file. Suppose I want to send file temp.jpg
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class send {
public final static int SOCKET_PORT = 8991; // you may change this
public final static String FILE_TO_SEND = "temp.jpg"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
// while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
// }
}
finally {
if (servsock != null) servsock.close();
}
}
}

Related

openning pdf file in android from server gives me this error document is empty

when I click button download, pdf opens but gives me this message document is empty 0ko plz if you any suggessions,I use my phone, and I send the acrobat reader adobe file in my phone and i have adobe acrobat in my phone..
this Mainactivity.java
package com.example.down1;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://172.16.2.138/upload/guide.pdf", "guide.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/uploade/" + "guide.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Intent intent = Intent.createChooser(pdfIntent, "Open File");
startActivity(pdfIntent);
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "uploade");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
this is my class filedownloader
package com.example.down1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to merge the two audio files into a single audio file in android?

I want to get two audio files as input, then merge them byte wise and save it as a single file.
In this code I have tried to do it in Java and it's working fine, but I don't know how to do it in android.
How to do it in android?
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class FileMixer {
public static void main(String[] args)
{
try
{
Path path1 = Paths.get("C:\\Srini\\Wav\\welcome.wav");
Path path2 = Paths.get("C:\\Srini\\Wav\\goodbye.wav");
String path3 ="C:\\Srini\\Wav\\srini12.wav";
File Newfilepath=new File(path3);
byte[] byte1 = Files.readAllBytes(path1);
byte[] byte2 = Files.readAllBytes(path2);
byte[] out = new byte[byte1.length];
for (int i=0; i<byte1.length; i++)
{
out[i] = (byte) ((byte1[i] + byte2[i]) >> 1);
}
InputStream byteArray = new ByteArrayInputStream(out);
AudioInputStream ais = AudioSystem.getAudioInputStream(byteArray);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE,Newfilepath);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
For combining two wav files use this code,
import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
public class WavAppender {
public static void main(String[] args) {
String wavFile1 = "D:\\wavOne.wav";
String wavFile2 = "D:\\wavTwo.wav";
try {
AudioInputStream clip1 = AudioSystem.getAudioInputStream(new File(wavFile1));
AudioInputStream clip2 = AudioSystem.getAudioInputStream(new File(wavFile2));
AudioInputStream appendedFiles =
new AudioInputStream(
new SequenceInputStream(clip1, clip2),
clip1.getFormat(),
clip1.getFrameLength() + clip2.getFrameLength());
AudioSystem.write(appendedFiles,
AudioFileFormat.Type.WAVE,
new File("D:\\wavAppended.wav"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
It is too late. But still, someone might need a proper solution. That is why I am suggesting using AudioMixer-android library. You can also perform a lot of audio processing things.

Creating a bitmap from png file stored at sdcard (Android)

Im trying to create a Bitmap from a Png file stored on the SD card and then set that Bitmap in an imageView.
But its not working.
Here's the code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import com.pxr.tutorial.xmltest.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
public class Getbackground {
URL url;
public static long downloadFile(URL url2) {
try {
URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
InputStream input = url.openStream();{
try {
File fileOnSD=Environment.getExternalStorageDirectory();
String storagePath = fileOnSD.getAbsolutePath();
OutputStream output = new FileOutputStream (storagePath + "/oranjelanbg.png");
try {
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.flush();
output.close();
//----------------------------------------------------------------------------------------------------------
Bitmap BckGrnd = BitmapFactory.decodeFile(storagePath + "/oranjelanbg.png");
ImageView BackGround=(ImageView)findViewById(R.id.imageView1);
BackGround.setImageBitmap(BckGrnd);
//----------------------------------------------------------=-----------------------------------------------
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
input.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} catch (MalformedURLException ex) {
throw new RuntimeException(ex);
} catch (IOException e) {
throw new RuntimeException(e);
}
return 0;
}
//-----------------------------------------------------------------------------------------
private static ImageView findViewById(int imageview1) {
// TODO Auto-generated method stub
return null;
}
//-----------------------------------------------------------------------------------------
}
The File does load on the SD card succesfully but I cant seem to get the img in the view.
You can't..
ImageView BackGround=(ImageView)findViewById(R.id.imageView1);
BackGround.setImageBitmap(BckGrnd);
How can you get the reference of ImageView in non activity class Getbackground?
You can only update UI component in MainUI Thread and if its in non Activity class then using reference (Context) of that calling activity class only.
So put this code in your Activity class after Getbackground completes.

FileWriter failing and not being caught by the Catch statement

here is my entire code (ps Im a noobie);
package xom.aaa.aaa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FilewritertestActivity extends Activity {
TextView textout1, textout2, textout3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.button1);
textout1 = (TextView) findViewById(R.id.textView1);
textout2 = (TextView) findViewById(R.id.textView2);
textout3 = (TextView) findViewById(R.id.textView3);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//--------- OutputStreamWriter ------------
try {
FileOutputStreamfOut=openFileOutput("settings1.dat", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write( "using fileoutput stream to write this to a file");
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
String datax = "";
StringBuffer buffer = new StringBuffer();
//--------- InputStreamReader -------------------
try {
FileInputStream fIn = openFileInput("settings1.dat");
Reader reader = new InputStreamReader(fIn);
int data = reader.read(); // reads the next char
while(data != -1){
buffer.append((char)data);
data = reader.read();
}
reader.close();
} catch ( Exception e) {
e.printStackTrace();
}
textout1.setText( buffer.toString());
//--------------- FileWriter ---------------
try {
FileWriter fw = new FileWriter("settings1.dat");
BufferedWriter out = new BufferedWriter(fw);
//BufferedWriter out = new BufferedWriter(new FileWriter("settings1.dat"));
out.write("a String");
out.close();
} catch (Exception e){
e.printStackTrace();
textout2.setText(e.toString());
}
}
});
}
}
Problem is FileWriter Not working ( for file "settings1.dat")
but OutputStreamWriter and InputStreamReader does work ( for file "settings1.dat")
the code shows writing then reading to file "settings1.dat" Is ok with Stream Witer/Reader...
But FileWriter code get error message Filenotfoundexception "read-only file system"
So why does one technique work on the same File and the other doesn´t
Can you please tell what Iam missing -- thanks Trevor
I'm guessing your problem is you just aren't getting an IOException. You could try changing
catch(IOException e)
to
catch(Exception e)
This will then catch all exceptions which extend the Exception object (it will not catch Errors though). However, I don't have the tools to test out your code so you will have to try it out yourself and post the results.
Best of luck.

how to upload the image into server

i tried to upload the image to the server for two days but i could not post the image .the coding is compiled and run sucessfully but the imag is not write into the server.
this is my coding:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class sde extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadtoUrl("http://
");
}
private void loadtoUrl(String string) {
// TODO Auto-generated method stub
try {
String pathToOurFile = "/sdcard/tamil.PNG";
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
byte[] bt=new byte[bis.available()];
HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
FileOutputStream input = (FileOutputStream) connection.getOutputStream();
input.write(bt);
} catch (MalformedURLException e) {
Context context = null;
int duration = 0;
Toast.makeText(context, "erro in writing", duration);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
here is a nice article, http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/. It contains an example that will upload an image and write it at server side. It works.
public boolean fileUpload(Map<String , String> params, ByteArrayOutputStream file, String link) throws Throwable{
Account user = Util.getAccount(getApplicationContext());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(link);
MultipartEntity multipartContent = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String , String> entry : params.entrySet()) {
multipartContent.addPart(entry.getKey(),new StringBody(entry.getValue(),Charset.forName(HTTP.UTF_8)));
}
}
byte[] data = file.toByteArray();
ByteArrayBody img = new ByteArrayBody(data, "capture.jpg");
multipartContent.addPart("image",img);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
return true;
}catch(Throwable e){
throw e;
}
}

Categories

Resources