0
我試圖在java中編寫一個服務器和一個客戶端來傳輸文件。但收到的文件很奇怪,看起來像是填充了奇怪的字節,它不會用任何應用程序打開,但它的大小與源文件完全相同。 我不知道問題出在哪裏!是關於編碼嗎?我應該使用哪一個流傳輸自定義文件(如jpeg或mp3)通過java中的網絡?
服務器端:
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) {
char sp = File.separatorChar;
String home = System.getProperty("user.home");
try {
ServerSocket server = new ServerSocket(5776);
while (true){
Socket connection = server.accept();
try {
String FileName=home+sp+"33.jpg";
File inputFile = new File(FileName);
FileInputStream Fin = new FileInputStream(inputFile);
long fileLength = inputFile.length();
byte[] bt= new byte[(int) fileLength];
DataOutputStream Oout = new DataOutputStream(connection.getOutputStream());
Oout.writeLong(fileLength);
Oout.write(bt);
Oout.flush();
Oout.close();
connection.close();
} catch (IOException ex) {}
finally {
try {
if(connection!= null) connection.close();
} catch (IOException e) {}
}
}
} catch (IOException e) {
System.err.println("There is a server on port 5776");
}
}
}
客戶端:
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
byte[] IP={(byte)192,(byte)168,1,7};
char sp = File.separatorChar;
String home = System.getProperty("user.home");
String SharingPathString = home+sp+"File Sharing";
String FileName = SharingPathString+sp+"file.jpg";
try {
InetAddress add = InetAddress.getByAddress(IP);
Socket theSocket= new Socket("Shayan-8",5776);
DataInputStream in= new DataInputStream(theSocket.getInputStream());
final long FileLength = in.readLong();
System.out.println("FileLength: "+FileLength);
File SharingPath = new File(SharingPathString);
if(!SharingPath.exists())
SharingPath.mkdir();
File outputFile = new File(FileName);
if(outputFile.exists())
outputFile.delete();
//outputFile.createNewFile();
FileOutputStream Fos = new FileOutputStream(FileName);
DataOutputStream dos = new DataOutputStream(Fos);
byte[] buffer = new byte[100];
int count=0;
long current=0;
while(current < FileLength && (count=in.read(buffer,0,(int)Math.min(FileLength-current, buffer.length)))!=-1)
{Fos.write(buffer, 0, count);
current+=count;
}
// while((count=in.read())!=-1)
// dos.write(count);
dos.close();
Fos.close();
} catch (UnknownHostException uhe) {
System.err.println(uhe);
} catch (IOException e) {
System.err.println(e);
}
}
}
哦!你是對的!我怎麼忘了那個? 真的很感謝,它的工作 :D – 2013-03-23 09:33:08
@Sathish我不必測試你的代碼,知道它是錯的。我讀過它;我讀過Javadoc;我已經回答了大約一百萬次這個問題。顯然你沒有測試過它是否有效。當你這樣做時,回來,我會告訴你爲什麼,以及如何解決它。 – EJP 2013-03-23 09:36:19
@EJP是的,我沒有測試 – Sathish 2013-03-23 10:17:21