■ ■ ■ ■ ■ ■
Projects/4_Server_for_file_transfers/src/com/exemple/Client.java
| 1 | + | package com.exemple; |
| 2 | + | |
| 3 | + | import javax.swing.*; |
| 4 | + | import java.awt.*; |
| 5 | + | import java.io.DataInputStream; |
| 6 | + | import java.io.DataOutputStream; |
| 7 | + | import java.io.File; |
| 8 | + | import java.io.FileInputStream; |
| 9 | + | import java.net.Socket; |
| 10 | + | |
| 11 | + | import static javafx.application.Platform.exit; |
| 12 | + | |
| 13 | + | public class Client { |
| 14 | + | private static DataOutputStream dataOutputStream = null; |
| 15 | + | private static DataInputStream dataInputStream = null; |
| 16 | + | private static String HOST= "localhost"; |
| 17 | + | |
| 18 | + | public static void main(String[] args) { |
| 19 | + | while (true) { |
| 20 | + | try { |
| 21 | + | JFileChooser file = new JFileChooser() { |
| 22 | + | @Override |
| 23 | + | protected JDialog createDialog(Component parent) throws HeadlessException { |
| 24 | + | // intercept the dialog created by JFileChooser |
| 25 | + | JDialog dialog = super.createDialog(parent); |
| 26 | + | dialog.setModal(true); // set modality (or setModalityType) |
| 27 | + | dialog.setAlwaysOnTop(true); |
| 28 | + | return dialog; |
| 29 | + | } |
| 30 | + | }; |
| 31 | + | file.setFileSelectionMode(JFileChooser.FILES_ONLY); |
| 32 | + | |
| 33 | + | int i = file.showSaveDialog(null); |
| 34 | + | if (1 == i) { |
| 35 | + | System.out.println("Arquivo não informado"); |
| 36 | + | exit(); |
| 37 | + | break; |
| 38 | + | } else { |
| 39 | + | Socket socket = new Socket(HOST, 5000); |
| 40 | + | |
| 41 | + | dataInputStream = new DataInputStream(socket.getInputStream()); |
| 42 | + | dataOutputStream = new DataOutputStream(socket.getOutputStream()); |
| 43 | + | |
| 44 | + | File arquivo = file.getSelectedFile(); |
| 45 | + | sendFile(arquivo.getPath()); |
| 46 | + | dataInputStream.close(); |
| 47 | + | dataInputStream.close(); |
| 48 | + | } |
| 49 | + | } catch (Exception e) { |
| 50 | + | e.printStackTrace(); |
| 51 | + | } |
| 52 | + | } |
| 53 | + | } |
| 54 | + | |
| 55 | + | private static void sendFile(String path) throws Exception{ |
| 56 | + | int bytes = 0; |
| 57 | + | File file = new File(path); |
| 58 | + | FileInputStream fileInputStream = new FileInputStream(file); |
| 59 | + | |
| 60 | + | // send file size |
| 61 | + | dataOutputStream.writeUTF(file.getName()); |
| 62 | + | dataOutputStream.writeLong(file.length()); |
| 63 | + | |
| 64 | + | // break file into chunks |
| 65 | + | byte[] buffer = new byte[4*1024]; |
| 66 | + | while ((bytes=fileInputStream.read(buffer))!=-1){ |
| 67 | + | dataOutputStream.write(buffer,0,bytes); |
| 68 | + | dataOutputStream.flush(); |
| 69 | + | } |
| 70 | + | fileInputStream.close(); |
| 71 | + | } |
| 72 | + | } |