Java 将文件从Pc发送到Android
我在Android手机上用Java编写了以下代码:Java 将文件从Pc发送到Android,java,android,sockets,Java,Android,Sockets,我在Android手机上用Java编写了以下代码: import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.os.Environment; import android.os.Looper; import android.util.Log; import java.io.BufferedOutputStream; import
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Handler;
public class Connection extends Thread {
private boolean isBinded = false;
private String IpAddress;
private Context cx;
private int num;
//private Socket socket;
private InputStreamReader inRead;
public ServerSocketChannel server;
private volatile boolean isRunning =true;
private File fileRecieved =null;
private FileOutputStream fos =null;
private BufferedOutputStream bos =null;
private File photoDir=null;
private ByteBuffer bufferByteSize=null;
private ByteBuffer bufferByte=null;
private MediaPlayer playMe=null;
private byte [] bytesToSend = null;
private MainActivity myActivity=null;
private Handler handler =null;
public Connection(String IpAddress, Context cx) {
this.IpAddress = IpAddress;
this.cx = cx;
myActivity = new MainActivity();
this.playMe = new MediaPlayer().create(cx, R.raw.sound1);
photoDir = new File(Environment.getExternalStorageDirectory(), "/RecievedPhotoes");
if (!photoDir.exists())
photoDir.mkdir();
}
@Override
public void run() {
Looper.prepare();
ToastHandler th = new ToastHandler(cx);//Toast handler is a class to handle toasts from threads
try {
Selector selector = Selector.open();
int[] ports = {5050, 4001, 6000};
// for (int port : ports) {
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(IpAddress, 5050));
server.register(selector, SelectionKey.OP_ACCEPT);
Log.d("msg", "1111");
th.showToast("Registered", 1000);
// }
while (true) {
Log.d("Selector : ", "selector.isOpen()");
selector.select();
Log.d("Selector : ", "selector.select()");
Set selectedkeys = selector.selectedKeys();
Log.d("Selector : ", "selector.selectedKeys();");
Iterator iterator = selectedkeys.iterator();
Log.d("Selector : ", "selectedkeys.iterator();");
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
Log.d("Selector : ", "iterator hasNext");
if (key.isAcceptable()) {
th.showToast("Accepted succefuuly ",1000);
SocketChannel client = server.accept();
if (client != null) {
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
bufferByteSize = ByteBuffer.allocate(1024);
client.read(bufferByteSize);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDate = sdf.format(new Date());
fileRecieved = new File(Environment.getExternalStorageDirectory(), photoDir+"/new_"+ currentDate+".jpg");
fos = new FileOutputStream(fileRecieved);
bos = new BufferedOutputStream(fos);
bufferByte = ByteBuffer.allocate(bufferByteSize.getInt());
client.read(bufferByte);
byte [] recevedData = new byte[bufferByteSize.getInt()];
bufferByte.get(recevedData);
bos.write(recevedData);
bos.flush();
bufferByteSize.clear();
bufferByte.clear();
if (client!= null) client.close();
int NotifID = 001;
Intent i = new Intent(cx, NotificationClass.class);
i.putExtra("NotifID", NotifID);
displayMyNotification mnotifyMe = new displayMyNotification(i, playMe, cx.getResources(), cx, NotifID);
mnotifyMe.start();
}
InputStreamReader(socket.getInputStream());
}
}
}
} catch (Exception e) {
th.showToast("Error" + e.getMessage().toString(),1000);
}
finally {
if (fos != null) try {
fos.close();
} catch (IOException e) {
th.showToast("Error" + e.getMessage().toString(),1000);
}
if (bos != null) try {
bos.close();
} catch (IOException e) {
th.showToast("Error" + e.getMessage().toString(),1000);
}
}
}
}
我在电脑上用Java编写了以下代码:
import com.sun.corba.se.spi.oa.OADefault;
import com.sun.xml.internal.stream.util.BufferAllocator;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import sun.java2d.pipe.BufferedBufImgOps;
/**
*
* @author laptop home
*/
public class Client {
public static void main(String args[]) throws IOException {
Socket s = null;
File file_to_send = null;
byte [] bytes_to_send = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
file_to_send = new File("C:\\Users\\laptop home\\Desktop\\yblutooth\\secureSyS\\lightbulb-png-825.png");
bytes_to_send = new byte [(int)file_to_send.length()];
fis = new FileInputStream(file_to_send);
bis = new BufferedInputStream(fis);
bis.read(bytes_to_send, 0, bytes_to_send.length);
s = new Socket("192.168.3.100", 5050);
System.out.println(s.toString());
Scanner sc = new Scanner(System.in);
System.out.print("Send File "+file_to_send.getPath().toString()+"??");
sc.next();
os = s.getOutputStream();
os.write(bytes_to_send.length);
os.flush();
os.write(bytes_to_send, 0, bytes_to_send.length);
os.flush();
}
catch (Exception e ) {
System.out.println(e);
}
finally{
if (s!=null){
s.close();
}
}
}
}
我想将一张照片从PC上的Java程序发送到Android程序。当我启动Android应用程序并运行线程时,什么都没有发生(等待新频道准备就绪)
当我在PC上启动Java程序时,它告诉我它已成功连接到手机,并在此处打印提示:
System.out.print("Send File "+file_to_send.getPath().toString()+"??");
当我键入任何文本并按Enter键时,程序将以绿色提示“Build Successfull…etc”结束,无错误
我去查看“ReceivedPhotoes”文件夹,但什么都没有
谁能告诉我是什么问题吗?
photoDir.mkdir()代码>。检查返回值。mkdir可能会失败。在这种情况下,你应该停下来。P请尝试并更新您的代码。检查文件夹“ReceivedPhotoes”,但没有任何内容代码>?什么是虚无?甚至文件夹也没有?什么都没有发生(等待新频道准备就绪)。
?在哪条语句上?您是否尝试使用断点?Scanner sc=new Scanner(System.in)代码>。您没有使用sc。