使用套接字编程将文件从android传输到pc

时间:2014-12-03 23:16:44

标签: java android file sockets transfer

我正在尝试执行以下代码将文件从android模拟器传输到pc。应用程序强制关闭,我在logcat中看到以下错误消息:

12-03 16:56:33.503: D/AndroidRuntime(1145): Shutting down VM
12-03 16:56:33.503: D/AndroidRuntime(1145): --------- beginning of crash
12-03 16:56:33.517: E/AndroidRuntime(1145): FATAL EXCEPTION: main
12-03 16:56:33.517: E/AndroidRuntime(1145): Process: com.example.androidfiletransfer, PID: 1145
12-03 16:56:33.517: E/AndroidRuntime(1145): java.lang.NullPointerException: Attempt to invoke              virtual method 'java.io.OutputStream java.net.Socket.getOutputStream()' on a null object reference
12-03 16:56:33.517: E/AndroidRuntime(1145):     at      com.example.androidfiletransfer.MainActivity$1.onClick(MainActivity.java:77)
12-03 16:56:33.517: E/AndroidRuntime(1145):     at android.view.View.performClick(View.java:4756)
12-03 16:56:33.517: E/AndroidRuntime(1145):     at    android.view.View$PerformClick.run(View.java:19749)
12-03 16:56:33.517: E/AndroidRuntime(1145):     at android.os.Handler.handleCallback(Handler.java:739)

控制台中显示以下消息:

Server started. Listening to the port 4444
Receiving...
mybytearray: 100000000
current: -1
bytes read: -1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at java.io.BufferedOutputStream.write(Unknown Source)
at Javafilereceive.main(Javafilereceive.java:53)

我尝试过研究这个错误,但我无法解决它。由于我是Android的新手,如果有人可以帮我解决这个问题,那将会很有帮助。

客户端代码:

package com.example.androidfiletransfer;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedInputStream;

public class MainActivity extends Activity {

//EditText textOut;
  TextView textIn;
  Socket client;
  FileInputStream fileInputStream;
  BufferedInputStream bufferedInputStream;
  OutputStream outputStream;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     if (android.os.Build.VERSION.SDK_INT > 9) {
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
  }

  //    textOut = (EditText)findViewById(R.id.textout);
        Button buttonSend = (Button)findViewById(R.id.send);
        textIn = (TextView)findViewById(R.id.textin);
        buttonSend.setOnClickListener(buttonSendOnClickListener);
  }

        Button.OnClickListener buttonSendOnClickListener
        = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
 // TODO Auto-generated method stub
 Socket socket;
 DataOutputStream dataOutputStream;
 DataInputStream dataInputStream;


 //File file = new File("/mnt/media_rw/sdcard/download/vivd_flowers-wide.jpg"); //create file    instance
 File dir = Environment.getExternalStorageDirectory();
 File file = new File(dir, "Sample.txt");

 System.out.println("file length: " + file.length());
 try {
 socket = new Socket("<ip address", 4444);
 byte[] mybytearray = new byte[(int) file.length()]; //create a byte array to file
 //  dataOutputStream = new DataOutputStream(socket.getOutputStream());
 // dataInputStream = new DataInputStream(socket.getInputStream());
 //  dataOutputStream.writeUTF(textOut.getText().toString());
 // textIn.setText(dataInputStream.readUTF());
    System.out.println("mybytearray in android: " + mybytearray.length);
    fileInputStream = new FileInputStream(file);
    bufferedInputStream = new BufferedInputStream(fileInputStream);  

    bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file
    System.out.println("Read into buffer");
    outputStream = client.getOutputStream();

    outputStream.write(mybytearray, 0, mybytearray.length); //write file to the output stream  byte by byte
    System.out.println("Written to buffer");
    outputStream.flush();
    bufferedInputStream.close();
    outputStream.close();
    client.close();

    textIn.setText("File Sent");
    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
    // TODO Auto-generated catch block
       e.printStackTrace();
   }
   }
   };
   }

服务器代码:

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Javafilereceive {

private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStream inputStream;
private static FileOutputStream fileOutputStream;
private static BufferedOutputStream bufferedOutputStream;
private static int filesize = 100000000; // filesize temporary hardcoded 
private static int bytesRead;
private static int current = 0;

public static void main(String[] args) throws IOException {


    serverSocket = new ServerSocket(4444);  //Server socket

    System.out.println("Server started. Listening to the port 4444");


    clientSocket = serverSocket.accept();


    byte[] mybytearray = new byte[filesize];    //create byte array to buffer the file

    inputStream = clientSocket.getInputStream();
    fileOutputStream = new FileOutputStream("D:\\output.jpg");
    bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

    System.out.println("Receiving...");
    System.out.println("mybytearray: " + mybytearray.length);

    //following lines read the input slide file byte by byte
    bytesRead = inputStream.read(mybytearray, 0, mybytearray.length);
    current = bytesRead;

    System.out.println("current: " + current);
    do {
        bytesRead = inputStream.read(mybytearray, current, (mybytearray.length - current));
        System.out.println("bytes read: " + bytesRead);
        if (bytesRead >= 0) {
            current += bytesRead;
        }
    } while (bytesRead > -1);


    bufferedOutputStream.write(mybytearray, 0, current);
    bufferedOutputStream.flush();
    bufferedOutputStream.close();
    inputStream.close();
    clientSocket.close();
    serverSocket.close();

    System.out.println("Sever recieved the file");

}
}

我已经放了一些println语句来查看是否从模拟器中选择了文件,但看起来并非如此。你能否告诉我如何在android中指定文件路径。

1 个答案:

答案 0 :(得分:3)

欢迎堆栈溢出!

您没有为初学者正确初始化套接字。

应该是

client = new Socket("192.18.2.22",4444);

其中“192.19.2.22”是您服务器的IP。

另外,尝试很好地格式化代码以使其可读。