繁体   English   中英

为什么我的代码仅发送大文件的一部分

[英]Why Is my code only sending part of a Large File

我正在尝试制作Java套接字文件服务器,但我已经走到了尽头,它似乎一直在起作用,直到在4080循环附近,然后似乎停止了,关于这种情况的任何想法? 这是我的代码:

public class FileSender extends Thread{

private final int PORT = 7777;
private Socket sock;
private DataInputStream fileStream;
private OutputStream out;
private File file ;

public void run() { 

    try {
       file = new File("path");

       if(file.exists()){
           System.out.println("Found File");

           if(file.canRead()){
               System.out.println("Can Read File");
           }
       }
    this.fileStream = new DataInputStream(new FileInputStream(file));



        sock = new Socket("localhost",PORT);
        out = sock.getOutputStream();

        copyStream(fileStream, out, file);

    } catch (IOException ex) {
        Logger.getLogger(FileSender.class.getName()).log(Level.SEVERE, null, ex);
    }

}

public void copyStream(DataInputStream in, OutputStream out, File file) throws IOException{

    byte[] buf = new byte[1024];

    int total = 0;

    while(file.getTotalSpace() != total){
        int r = in.read(buf);


        if(r != -1){
        out.write(buf, 0, r);
        }

        total += r;
    }

    out.flush();

    System.out.println("Total was:" + total);

}

}

这是我的服务器:

public class FileReceiver extends Thread {

private final int PORT = 7777;
private ServerSocket sSoc;
private DataInputStream in;

public void run() {

    try {

        byte[] buf = new byte[1024];

        sSoc = new ServerSocket(PORT);

        Socket conn = sSoc.accept();

        in = new DataInputStream(new BufferedInputStream(conn.getInputStream()));

        File file = new File("C:\\test.rar");

        if (!file.exists()) {
            file.createNewFile();
        }

        if (file.canWrite()) {

            FileOutputStream fos = new FileOutputStream(file);

            int x= 0 ;
            do {

                in.read(buf);
                System.out.println(x + " : " + buf);

                fos.write(buf);
                x++;

            } while (in.read(buf) != -1);

            System.out.println("Complete");
        }

    } catch (IOException ex) {
        Logger.getLogger(FileReceiver.class.getName()).log(Level.SEVERE, null, ex);
    }

}

}

编辑:程序将发送一个小的文本文件,但是onlky发送一个更大的文件的一部分。

您在copyStreamwhile循环中的copyStream似乎不正确。 请尝试将其更改为以下内容并尝试。

public void copyStream(DataInputStream in, OutputStream out, File file) throws IOException{

    byte[] buf = new byte[1024];

    int total = 0;

    while(true){
        int r = in.read(buf);    

        if(r != -1){
            out.write(buf, 0, r);
            total += r;
        } else {
            break;
        }  

    }

问题出在我的服务器上,我在两次调用in.read()时强制使用大于单个缓冲区大小的任何值来丢失段。

暂无
暂无

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

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