我目前正在尝试创建一个文件传输程序,可以将文件从一个位置传输到另一个位置。该程序适用于.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();
}
}
答案 0 :(得分:1)
一个问题是,在从InputStream读取时,您正在覆盖buffer
的内容
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);
InputStream #read将第二个param表示为偏移量,它将存储在字节数组中,在您的情况下,偏移量始终为0
,因此它将在每次迭代中覆盖。
我建议简化从InputStream读取和写入OutputStream
的逻辑byte[] buffer = new byte[16384];
while ((byteread = is.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, byteread);
}
out.flush();
希望这有帮助。