繁体   English   中英

Android和PC之间通过TCP连接发送的文件开头不需要的字符

[英]Unwanted characters at the start of file, sent with TCP connection, between Android & PC

所以我想从PC(Windows)向Android手机发送一个简单的文本文件。 我将在Stackoverflow上找到的部分代码放在一起。 我的问题是当我发送此文本文件时:

testing, sending this text. testing, sending this text.

我在客户端获得此文件:

’ testing, sending this text. testing, sending this text.

感谢您可能提出的任何解决方案。

PS。 我知道我可以删除第一个字符,但是为什么会这样呢? 难道我做错了什么 ?

更多信息:

  1. 当我发送图像时,问题仍然存在。 图像将在客户端损坏。
  2. 在客户端收到文件时,文件总长4个字节

这是我的服务器代码(在Java中):

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer extends Thread {

    public static final int SERVERPORT = 8901;

    public static void main( String [] args) {

        try {
            System.out.println("S: Connecting...");

            ServerSocket serverSocket = new ServerSocket(SERVERPORT);
            System.out.println("S: Socket Established...");

            Socket client = serverSocket.accept();
            System.out.println("S: Receiving...");

            ObjectOutputStream put = new ObjectOutputStream(
                    client.getOutputStream());

            String s = "1.txt";
            String str = "C:/";
            String path = str + s;
            System.out.println("The requested file is path: " + path);
            System.out.println("The requested file is : " + s);

            File myFile = new File (path); 
            byte [] mybytearray  = new byte [(int)myFile.length()];
            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);

            bis.read(mybytearray,0,mybytearray.length);
            OutputStream os = client.getOutputStream();

            System.out.println("Sending...");

            os.write(mybytearray,0,mybytearray.length);
            os.flush();
            client.close();


        } catch (Exception e) {
            System.out.println("S: Error");
            e.printStackTrace();
        } finally {

        }
    }
}

这是我的客户端应用(在android上):

public class MainActivity extends Activity {

    int u;
    byte[] aByte = new byte[1];
    int bytesRead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread( new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Socket sock = null;
                BufferedInputStream bis = null;
                //              Debug.waitForDebugger();

                try {
                    sock = new Socket("192.168.1.53", 8901);
                    bis = new BufferedInputStream(sock.getInputStream());


                    String path = "/mnt/sdcard/2.txt";
                    FileOutputStream fs = new FileOutputStream(new File(path));
                    BufferedOutputStream bos = new BufferedOutputStream(fs);

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    try {

                        bytesRead = bis.read(aByte, 0, aByte.length);

                        do {
                            baos.write(aByte);
                            bytesRead = bis.read(aByte);
                        } while (bytesRead != -1);

                        bos.write(baos.toByteArray());
                        bos.flush();
                        bos.close();
                        sock.close();
                    } catch (IOException ex) {
                        // Do exception handling
                    }

/*
                    byte jj[] = new byte[1024];
                    while ((u = get.read(jj, 0, 1024)) != -1) {
                        fs.write(jj, 0, u);
                    }
                    fs.close();
                    System.out.println("File received");
                    s.close();*/
                } catch (Exception e) {
                    e.printStackTrace();
                    //                  System.exit(0);
                }

            }
        }).start();
    }


}

这是由以下未使用的代码引起的:

ObjectOutputStream put = new ObjectOutputStream(
                client.getOutputStream());

该语句写一个对象流头。 浪费时间和空间,并且由于没有在对等方使用ObjectInputStream而破坏了数据。 删除它。

除此之外,您的代码还表现出通常的问题。

byte [] mybytearray  = new byte [(int)myFile.length()];

您不需要文件大小的数组:8192就可以了。 同样在这里,您假设文件大小为<2GB。

FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);

在此应用程序中,您实际上并不需要BufferedInputStream。

bis.read(mybytearray,0,mybytearray.length);

在这里,您假设read()填充了缓冲区。 它不执行此操作,仅传输至少一个字节或返回-1。

os.write(mybytearray,0,mybytearray.length);

同上。 在Java中复制流的规范方法如下:

int count;
byte[] buffer = new byte[8192]; // or whatever you like, anything > 0. Heroic sizes buy you nothing
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

您的客户端代码甚至更糟。 您可以将其简化为与输入和输出不同的上述完全相同的循环。 您根本不需要ByteArrayOutputStream

我的猜测是,如果您在android中创建了文本文件,则可能是以UTF格式创建的。

但是,如果您在Windows中创建它并将其复制到您的计算机上,则格式可能会有所不同,这就是为什么要添加额外字符的原因。

您可以尝试编写文本并确保格式为UTF-8,然后查看是否仍会发生这种情况。

暂无
暂无

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

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