1:客户端程序
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
int longth = 0;
try {
Socket socket = new Socket("127.0.0.1",4700);
//首先获得文件输入流
FileInputStream fileInputStream = new FileInputStream("D:/一般的软件/Thunder_7.9.42.5050Preview.exe");
//再获得文件输出流
OutputStream outputStream = socket.getOutputStream();
byte[] bt = new byte[1024000];
while((longth = fileInputStream.read(bt)) > 0){
**/**
* 这句话outputStream.write(bt,0,longth)非常重要,不能够直接写成outputStream.write(bt)把整个数组给传送过去,
* 因为上面的read方法最后一次并不能够全部写满整个数组
* 也就是说,你写入了多少就传输多少
*/**
outputStream.write(bt,0,longth);
outputStream.flush();
}
fileInputStream.close();
outputStream.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2:服务器端程序
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket acceptClient = null;
try {
serverSocket = new ServerSocket(4700);
acceptClient = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("创建服务器端失败,或者监听失败");
}
try {
InputStream inputStream = acceptClient.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("D:/一般的软件/迅雷7/Thunder_7.9.42.5050Preview.exe");
byte[] bt = new byte[1024000];
int length = 0;
double count = 0;
System.out.println("开始接收接收接收接收数据");
while((length = inputStream.read(bt)) > 0){
*/**
* 这句话outputStream.write(bt,0,longth)非常重要,不能够直接写成outputStream.write(bt)把整个数组给传送过去,
* 因为上面的read方法并不能够确保每次都能写满整个数组
* 也就是说,你存多少进数组,就取多少写入文件
*/*
fileOutputStream.write(bt,0,length);
fileOutputStream.flush();
count += length;
System.out.println("接收了::" + count + "字节");
}
inputStream.close();
fileOutputStream.close();
acceptClient.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
3:总结:在写的过程中遇到一个致命的问题就是把fileOutputStream.write(bt,0,length);写成了fileOutputStream.write(bt),这样就会使得收到的文件比原来的文件打好几倍。
而且,文件复制或者是文件网络传输基本上都是使用“字节流 + 字符数组”的形式来传输。确保不会乱码和丢失。