I am currently trying to to create a file transfer program which could transfer files from one location to another. The program works for .txt files, but for other extensions, such as .exe, the transferred files don't open properly.Can anyone spot the problem with my code? Thanks!
Server code:
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");
}
}
Client code:
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();
}
}
One problem is you are overwriting the content of your buffer
while reading from InputStream
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 states second param as offset where it will be stored in byte array and in your case offset is always 0
, so it will overwrite in each iteration.
I would suggest to simplify your logic of reading from InputStream and writing to OutputStream
byte[] buffer = new byte[16384];
while ((byteread = is.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, byteread);
}
out.flush();
Hope this helps.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments