packagecom.zhao.updata;importjava.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintStream;importjava.net.Socket;importjava.net.UnknownHostException;importjava.util.Scanner;public classUpdata_Client {publicUpdata_Client() {
}
public static void main(String[] args) throwsIOException {//* 1.提示要上傳的路徑,驗證檔案夾是否存在或者是否是路徑
File filename =getFile();//* 2.發送檔案名到服務端
Socket socket = new Socket("127.0.0.1", 65534);
BufferedReader br= new BufferedReader(newInputStreamReader(socket.getInputStream()));
PrintStream ps= newPrintStream(socket.getOutputStream());
ps.println(filename.getName());//* 3.接受結果,如果存在給予提示,程式直接退出
String result =br.readLine();boolean flag =isfile_server(socket, br, ps, result, filename);//* 4.如果不存在,定義FileInputStream 讀取檔案,寫出到網絡
if(flag) {
FileInputStream fis= newFileInputStream(filename);byte[] arr = new byte[8192];intlen;//double progress=0;//進度//int sump=fis.available();//傳回位元組檔案輸入流中可讀取的位元組數
while ((len = fis.read(arr)) != -1) {
ps.write(arr,0, len);//progress=len/sump;//進度//System.out.println("目前進度:"+progress+"%");
}
System.out.println("傳輸完成");
fis.close();
socket.close();
}
}private static booleanisfile_server(Socket socket, BufferedReader br, PrintStream ps, String result, File filename)throwsIOException {if ("ok".equals(result)) {
System.out.println("您上傳的檔案伺服器端已經存在,請不要重複上傳!");
System.out.println("\n\n請您重新輸入!");//System.out.println("\n\n請您重新輸入或輸入Q退出!");//if("Q".equals(br.readLine())){//socket.close();//System.exit(0);//退出程式//}
socket.close();
}else if ("no".equals(result)) {return true; //可以上傳
}return false;
}private staticFile getFile() {
Scanner sc= newScanner(System.in);
System.out.println("請輸入要上傳的檔案路徑:");while (true) {
String line=sc.nextLine();
File file= newFile(line);if (!file.exists()) {
System.out.println("您輸入的檔案路徑不存在!");
}else if(file.isDirectory()) {
System.out.println("您輸入的是檔案夾路徑,請輸入檔案路徑!");
}else{returnfile;
}
}
}
}