帮忙看看有什么问题,文件拷贝地方是不是不对,运行无结果
客户端向服务器上传文件
服务端代码
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(20334);
while(true) {
final Socket socket = server.accept();
new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps;
ps = new PrintStream(socket.getOutputStream());
File dir = new File("update");
File file = new File(dir,br.readLine());
if(!file.exists()) {
ps.println("no");
}else {
ps.println("yes");
}
int len = 0;
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
while ((len = bis.read()) != -1)
bos.write(len);
bis.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
客户端代码
public static void main(String[] args) throws UnknownHostException, IOException {
//创建客户端
Socket socket = new Socket("127.0.0.1",20334);
//创建客户端输入输出流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
System.out.println("请输入要上传文件的路径");
//创建键盘录入对象
Scanner scanner = new Scanner(System.in);
//创建文件对象判断文件是否存在以及是否是文件夹
while(true){
File file = new File(scanner.nextLine());
if(!file.exists()||file.isDirectory()) {
System.out.println("你输入的路径有有误,请重新输入");
}else {
ps.println(scanner.nextLine());
break;
}
}
if("yes".equals(br.readLine())) {
System.out.println("您上传的文件已存在,请不要重复上传");
return;
}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(scanner.nextLine())) ;
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
int len = 0;
while((len=bis.read()) != -1)
bos.write(len) ;
bis.close();
socket.close();
}
|
|