package demo05;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class UPload implements Runnable {
private Socket s;
private FileOutputStream fos;
public UPload(Socket s) {
this.s = s;
}
public void run() {
try {
// 3.获取输入流
InputStream in = s.getInputStream();
// 4.获取文件夹,如果不存在就创建
File f = new File("f:\\aaa");
if (!f.exists()) {
f.mkdirs();
}
// 5.创建文件输出流
String filename = "oracle" + System.currentTimeMillis() + new Random().nextInt(99999) + ".png";
fos = new FileOutputStream(f + File.separator + filename);
// 6.写入数据
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
fos.write(b, 0, len);
}
// 服务器给客服端回复(上传成功)
OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
// 释放资源
fos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package demo05;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class test {
public static void main(String[] args) throws IOException {
ServerSocket ser =new ServerSocket(8888);
while(true){
Socket s =ser.accept();
UPload u =new UPload(s);
Thread t =new Thread(u);
t.start();
}
}
}