我在套接字上创建一个传输文件的程序。保存文件后,其大小会增加。这是源代码Server-class:
import java.io.*;
import java.net.*;
public class FileServer {
static final int port = 3000;
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(port);
Socket client = server.accept();
DataInputStream input = new DataInputStream(client.getInputStream());
int size = 2358464;
byte[] buffer = new byte[size];
while (true) {
int receivedBytes = input.read(buffer);
if (receivedBytes == -1) break;
}
input.close();
client.close();
server.close();
FileOutputStream fos = new FileOutputStream("D:\\Projects\\Courses\\loadedFile.s3db");
fos.write(buffer);
fos.close();
} catch (Exception ex) {
System.out.println(ex);
}
}}
客户端级:
import java.io.*;
import java.net.*;
public class Client {
public static void main(java.lang.String[] args) throws FileNotFoundException {
final int port = 3000;
try {
File file = new File("D:\\Projects\\Courses\\src\\Data", "data.s3db");
FileInputStream input = new FileInputStream(file);
int size = (int) file.length();
byte[] buffer = new byte[size];
Socket socket = new Socket("127.0.0.1", port);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
while (true) {
int receivedBytes = input.read(buffer);
if (receivedBytes == -1) {
break;
}
if (receivedBytes > 0) {
out.write(buffer, 0, receivedBytes);
}
}
input.close();
out.close();
socket.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果,转移后最初大小为6 kb的文件开始重2304 kb。在什么阶段文件大小增加?如何避免这种情况?