简体   繁体   English

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

[英]Transfer file from android to pc using socket programming

I'm trying to execute the below code to transfer a file from android emulator to pc. 我正在尝试执行以下代码,将文件从android模拟器传输到pc。 The application force closes and i see the following error message in logcat: 应用程序强制关闭,我在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)

And the following message in the console: 并在控制台中显示以下消息:

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)

I tried researching on this error but im unable to resolve it. 我尝试研究此错误,但无法解决。 Since im new to android, it would be of great help if someone could help me out with this. 由于我是android的新手,所以如果有人可以帮助我,这将是非常有用的。

Client side code: 客户端代码:

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

Server code: 服务器代码:

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");

}
}

I had put some println statements to see if the file is picked from the emulator, but looks like its not. 我放置了一些println语句,以查看是否从仿真器中选取了该文件,但是看起来好像不是。 Can you also let me know how to specify the file path in android. 您还可以让我知道如何在android中指定文件路径吗?

Welcome to stack overflow! 欢迎堆栈溢出!

You did not initialize your socket correctly for starters. 您没有为初学者正确初始化套接字。

Should be 应该

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

Where "192.19.2.22" is the ip of your server. 其中“ 192.19.2.22”是服务器的IP。

Also,try to format your code nicely to make it readable. 另外,请尝试很好地格式化代码以使其可读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM