java - 如何正确写入文件数据?

标签 java io filestream large-files

我的应用程序无法通过套接字连接正确传输数据并将其正确写入文件。超过大约 65,535 字节的文件会被损坏,并且不再被设计用来运行它们的程序识别。

我已经能够成功发送小型 .doc 和 .txt 文件,但 .mp3 .wmv .m4a .avi 以及其他任何文件都不起作用。较大的文档也没有。

我在互联网上寻找了解决这个问题的方法。我已经反复调整I/O代码来解决这个问题,但仍然不起作用!以下是父类(super class)中处理发送和接收文件的 I/O 代码。如果您需要更多信息/代码的其他部分,请告诉我。

protected void sendFile() throws IOException {
    byte[] bytes = new byte[(int) file.length()];
    buffin = new BufferedInputStream(new FileInputStream(file));
    int bytesRead = buffin.read(bytes,0,bytes.length);
    System.out.println(bytesRead);
    out = sock.getOutputStream();
    out.write(bytes,0,fileBytes);
    out.flush();
    out.close();
}

protected void receiveFile() throws IOException {
    byte[] bytes = new byte[fileBytes];
    in = sock.getInputStream();
    for(int i=0;i<fileBytes;i++) {
        in.read(bytes);
    }
    fos = new FileOutputStream("/Datawire/"+fileName);
    buffout = new BufferedOutputStream(fos);
    buffout.write(bytes,0,fileBytes);
    buffout.flush();
    buffout.close();
}

更新的代码(有效):

    protected void sendFile() throws IOException {
    if((file.length())<63000) {
        byte[] bytes = new byte[(int)file.length()];
        buffin = new BufferedInputStream(new FileInputStream(file));
        buffin.read(bytes,0,bytes.length);
        out = sock.getOutputStream();
        out.write(bytes,0,bytes.length);
        out.close();
    } else {
        byte[] bytes = new byte[32000];
        buffin = new BufferedInputStream(new FileInputStream(file));
        out = sock.getOutputStream();
        int bytesRead;
        while((bytesRead = buffin.read(bytes))>0) {
            out.write(bytes,0,bytesRead);
        }
        out.close();
    }
}

protected void receiveFile() throws IOException {
    if(fileBytes<63000) {
        byte[] bytes = new byte[32000];
        in = sock.getInputStream();
        System.out.println(in.available());
        in.read(bytes,0,fileBytes);
        fos = new FileOutputStream("/Datawire/"+fileName);
        buffout = new BufferedOutputStream(fos);
        buffout.write(bytes,0,bytes.length);
        buffout.close();
    } else {
        byte[] bytes = new byte[16000];
        in = sock.getInputStream();
        fos = new FileOutputStream("/Datawire/"+fileName);
        buffout = new BufferedOutputStream(fos);
        int bytesRead;
        while((bytesRead = in.read(bytes))>0) {
            buffout.write(bytes,0,bytesRead);
        }
        buffout.close();
    }
}

最佳答案

问题是您只发送了其中的一部分。也就是说,您只发送了 64k 的文件。如果文件大于 64k,另一端将永远看不到它。

您想要连续从 BufferedInputStream 读取数据,直到 read() 返回小于长度或 -1。

关于java - 如何正确写入文件数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6598529/

相关文章:

Java 文件到二进制的转换

c - 文件输出异常

c# - File.ReadLines 不用加锁吗?

java - 如何使用 JAX-RS 从我的 Java 服务器端返回一个 Zip 文件?

java - 在 IntelliJ IDEA 中重命名模块

java - 谁对 URLencoding 进行解码?

java - Spring 休息API : Password encoding

java - UrlClassLoader 委托(delegate)和继承层次

c# - 使用 FileStream.WriteAsync() 时,再次调用该方法时会发生什么