java Socket 文件传输(二)
int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
String filePath = "D:/temp/"+GetDate.getDate()+"SJ"+new Random().nextInt(10000)+".zip";
try {
try {
dis = new DataInputStream(socket.getInputStream());
File f = new File("D:/temp");
if(!f.exists()){
f.mkdir();
}
/*
* 文件存储位置
*/
fos = new FileOutputStream(new File(filePath));
inputByte = new byte[1024];
System.out.println("开始接收数据...");
while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
fos.write(inputByte, 0, length);
fos.flush();
}
System.out.println("完成接收:"+filePath);
} finally {
if (fos != null)
fos.close();
if (dis != null)
dis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
时间工具类:
[java]
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 时间工具类
* @author admin_Hzw
*
*/
public class GetDate {
/**
* 时间格式到毫秒
*/
private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
public static String getDate(){
return df.format(new Date());
}
}