Advertisement
dig090

Transfer Client

Dec 9th, 2011
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. package com.j256.ormlite.jdbc;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedReader;
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.InputStreamReader;
  8. import java.io.PrintWriter;
  9. import java.net.InetAddress;
  10. import java.net.Socket;
  11.  
  12. public class Client {
  13.  
  14.     public static void main(String[] args) throws Exception {
  15.         BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
  16.         System.out.print("Enter File Name :");
  17.         System.out.flush();
  18.         String fileName = console.readLine();
  19.  
  20.         // see if the file exists up front
  21.         File file = new File(fileName);
  22.         // turn this into a file in the current directory -- you prolly don't want this
  23.         file = new File(file.getName());
  24.        
  25.         // see if it exists _before_ we connect
  26.         if (file.exists()) {
  27.             String Option;
  28.             System.out.println("File '" + fileName + "' already exists. Want to overWrite (Y/N) ?");
  29.             System.out.flush();
  30.             Option = console.readLine();
  31.             if (Option == "N") {
  32.                 return;
  33.             }
  34.         }
  35.  
  36.         // connect to the server
  37.         Socket socket = new Socket(InetAddress.getLocalHost(), 8080);
  38.         BufferedInputStream reader = new BufferedInputStream(socket.getInputStream());
  39.         PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
  40.  
  41.         writer.println(fileName);
  42.         int val = reader.read();
  43.         if (val == 0) {
  44.             System.out.println("File not found on Server ...");
  45.         } else if (val == 1) {
  46.             System.out.println("Receiving File ...");
  47.             FileOutputStream fileout = new FileOutputStream(file);
  48.             byte[] bytes = new byte[1024];
  49.             int byteCount = 0;
  50.             while (true) {
  51.                 int numRead = reader.read(bytes);
  52.                 if (numRead <= 0) {
  53.                     break;
  54.                 }
  55.                 byteCount += numRead;
  56.                 fileout.write(bytes, 0, numRead);
  57.             }
  58.             fileout.close();
  59.             System.out.println("Received " + byteCount + " bytes to file " + fileName);
  60.         } else {
  61.             System.err.println("Val == " + val);
  62.         }
  63.     }
  64. }
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement