Ich versuche gerade, ein Dateiübertragungsprogramm zu erstellen, das Dateien von einem Ort zu einem anderen übertragen kann. Das Programm funktioniert für TXT-Dateien, aber für andere Erweiterungen wie .exe, öffnen die übertragenen Dateien nicht richtig. Kann jemand das Problem mit meinem Code erkennen? Vielen Dank!Java sendet und empfängt Dateien über Sockets
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();
}
}
Wow, es funktioniert jetzt, vielen Dank! –
Froh, dass es dir geholfen hat :) – Sanjeev