Java基於Socket檔案傳輸示例
阿新 • • 發佈:2019-02-04
{
// 選擇進行傳輸的檔案
String filePath = "D:\\lib.rar";
File fi = new File(filePath);
System.out.println("檔案長度:" + (int) fi.length());
// public Socket accept() throws
// IOException偵聽並接受到此套接字的連線。此方法在進行連線之前一直阻塞。
s = ss.accept();
System.out.println("建立socket連結");
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new DataOutputStream(s.getOutputStream());
//將檔名及長度傳給客戶端。這裡要真正適用所有平臺,例如中文名的處理,還需要加工,具體可以參見Think In Java 4th裡有現成的程式碼。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意關閉socket連結哦,不然客戶端會等待server的資料過來,
// 直到socket超時,導致資料不完整。
fis.close();
s.close();
System.out.println("檔案傳輸完成");
}
// 選擇進行傳輸的檔案
String filePath = "D:\\lib.rar";
File fi = new File(filePath);
System.out.println("檔案長度:" + (int) fi.length());
// public Socket accept() throws
// IOException偵聽並接受到此套接字的連線。此方法在進行連線之前一直阻塞。
s = ss.accept();
DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
dis.readByte();
DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
DataOutputStream ps = new
//將檔名及長度傳給客戶端。這裡要真正適用所有平臺,例如中文名的處理,還需要加工,具體可以參見Think In Java 4th裡有現成的程式碼。
ps.writeUTF(fi.getName());
ps.flush();
ps.writeLong((long) fi.length());
ps.flush();
int bufferSize = 8192;
while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}
if (read == -1) {
break;
}
ps.write(buf, 0, read);
}
ps.flush();
// 注意關閉socket連結哦,不然客戶端會等待server的資料過來,
// 直到socket超時,導致資料不完整。
fis.close();
s.close();
System.out.println("檔案傳輸完成");
}