0

我已经编写了一个代码来在两个客户端和服务器之间发送和接收文件,但我希望这两个功能都在一个程序中。所以我写了一个包含发送和接收函数的单独类。我已经声明了两个变量sendFilePathreceiveFilePath. 我调用了该方法 transfer(String sendFileName, String receiveFileName)并为这些变量赋值,但它显示为空。

我怎样才能做到这一点?

实际上我想发送sendFilePathrf.receive();和方法如何完成receiveFilePathsf.send();

class TransferFile implements Runnable
{    
    Thread thread;

    String sendFilePath, receiveFilePath;
    SendFile sf = new SendFile();
    ReceiveFile rf = new ReceiveFile();

    public void TransferFileCreateThread(String name)
    {
        thread = new Thread(this,name);
        thread.start();
    }
    public void run()
    {
        rf.receive(sendFilePath);
        sf.send(receiveFilePath);
    }

    public void transfer(String sendFileName, String receiveFileName)
    {
        try
        {
            sendFilePath = sendFileName;
            receiveFilePath = receiveFileName;

            TransferFile t1 = new TransferFile();
            TransferFile t2 = new TransferFile();
            t1.TransferFileCreateThread(sendFilePath);
            t2.TransferFileCreateThread(receiveFilePath);
        }
        catch(Exception e)
        {
        }
    }
}
4

1 回答 1

0

在这里,您正在创建新对象 t1 和 t2,而不是为对象 t1 和 t2 分配值。

你可以这样做..

class TransferFile implements Runnable
{    
    Thread thread;

    private String sendFilePath=null;
    private String receiveFilePath=null;
    SendFile sf = new SendFile();
    ReceiveFile rf = new ReceiveFile();

    public void TransferFileCreateThread(String name)
    {
        thread = new Thread(this,name);
        thread.start();
    }
    public void run()
    {
        rf.receive(sendFilePath);
        sf.send(receiveFilePath);
    }
    public void setSendFilePath(String filePath){
         this.sendFilePath=filePath;
    }
    public void setReceiveFilePath(String filePath){
         this.receiveFilePath=filePath;
    }
    public void transfer(String sendFileName, String receiveFileName)
    {
        try
        {
            sendFilePath = sendFileName;
            receiveFilePath = receiveFileName;

            TransferFile t1 = new TransferFile();
            t1.setSendFilePath(sendFilePath);
            t1.setReceiverFilePath(receiveFilePath);
            TransferFile t2 = new TransferFile();
            t1.setSendFilePath(sendFilePath);
            t1.setReceiverFilePath(receiveFilePath);
            t1.TransferFileCreateThread(sendFilePath);
            t2.TransferFileCreateThread(receiveFilePath);
        }
        catch(Exception e)
        {
        }
    }
}

希望能帮助到你..

您可以做的另一件事是您可以在 t1 和 t2 上调用 tranfer 方法,以便将值分配给字符串对象。

于 2013-08-26T13:23:26.073 回答