【发布时间】:2016-12-08 13:09:15
【问题描述】:
我目前正在尝试创建一个文件传输程序,该程序可以将文件从一个位置传输到另一个位置。该程序适用于 .txt 文件,但对于其他扩展名,例如 .exe,传输的文件无法正常打开。有人能发现我的代码的问题吗?谢谢!
服务器代码:
import java.io.*;
import java.net.*;
public class SendFile{
static ServerSocket receiver = null;
static OutputStream out = null;
static Socket socket = null;
static File myFile = new File("C:\\Users\\hieptq\\Desktop\\AtomSetup.exe");
/*static int count;*/
static byte[] buffer = new byte[(int) myFile.length()];
public static void main(String[] args) throws IOException{
receiver = new ServerSocket(9099);
socket = receiver.accept();
System.out.println("Accepted connection from : " + socket);
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream in = new BufferedInputStream(fis);
in.read(buffer,0,buffer.length);
out = socket.getOutputStream();
System.out.println("Sending files");
out.write(buffer,0, buffer.length);
out.flush();
/*while ((count = in.read(buffer)) > 0){
out.write(buffer,0,count);
out.flush();
}*/
out.close();
in.close();
socket.close();
System.out.println("Finished sending");
}
}
客户端代码:
import java.io.*;
import java.net.*;
public class ReceiveFile{
static Socket socket = null;
static int maxsize = 999999999;
static int byteread;
static int current = 0;
public static void main(String[] args) throws FileNotFoundException, IOException{
byte[] buffer = new byte[maxsize];
Socket socket = new Socket("localhost", 9099);
InputStream is = socket.getInputStream();
File test = new File("D:\\AtomSetup.exe");
test.createNewFile();
FileOutputStream fos = new FileOutputStream(test);
BufferedOutputStream out = new BufferedOutputStream(fos);
byteread = is.read(buffer, 0, buffer.length);
current = byteread;
do{
byteread = is.read(buffer, 0, buffer.length - current);
if (byteread >= 0) current += byteread;
} while (byteread > -1);
out.write(buffer, 0, current);
out.flush();
socket.close();
fos.close();
is.close();
}
}
【问题讨论】:
标签: java sockets server client