Server Socket

Ola galera estou fazendo um server de arquivos mas esta dando um erro, quando eu envio um arquivo ele não salva e da um erro:

Erro no console:

Erro: FileNotFoundException

Script Inteira:

package Servidor;

import java.awt.Menu;
import java.awt.SystemColor;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.channels.FileChannel;
import java.util.Random;
import java.util.Scanner;

import javax.swing.JFileChooser;

public class Client{

    private Socket socket;
    private ObjectOutputStream objectStream;
    
    public Client() throws UnknownHostException, IOException {
        System.out.println("Iniciando...");
        this.socket = new Socket("192.168.0.108", 5566);

    this.objectStream = new ObjectOutputStream(socket.getOutputStream());
    
    new Thread(new ListenerSocket(socket)).start();

Scanner sc1 = new Scanner(System.in);
    
    String name = InetAddress.getLocalHost().getHostName();
    
    this.objectStream.writeObject(new Arquivo(name));

    int option = 0;
    while (option != 1) {
        System.out.print("Digite: 1 para Sair | 2 para Enviar");
        System.out.println("");
        option = sc1.nextInt();
        if(option == 2){
            send(name);
        }else if(option == 1){
            System.out.println("Desconectado!");
            System.out.println("Bye! :)");
            System.exit(0);
        }
    }
    
    
    }
    
    
    private void send(String name) throws IOException {
        
        JFileChooser fileChooser = new JFileChooser();
        
        int opt = fileChooser.showOpenDialog(null);
        if(opt == JFileChooser.APPROVE_OPTION){
            File file = fileChooser.getSelectedFile();
            
            this.objectStream.writeObject(new Arquivo(name,file));
        }
    }

    private class ListenerSocket implements Runnable{
        
        private ObjectInputStream inputStream;
        
        public ListenerSocket(Socket socket) throws IOException{
            this.inputStream = new ObjectInputStream(socket.getInputStream());
            
        }
        public void run(){
            Arquivo message = null;
            
            try {
                while ((message = (Arquivo) inputStream.readObject()) != null) {
                    System.out.println("");
                    System.out.println("");
                    System.out.print("Você recebeu um arquivo de: "+message.getClient());
                    System.out.println("");
                    System.out.print("Nome do arquivo: "+message.getFile().getName());
                    System.out.println("");
                    
                    salve(message);
                }
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        private void salve(Arquivo message){
            
            try {
                
                Thread.sleep(new Random().nextInt(1000));
                
                long time = System.currentTimeMillis();
                
                FileInputStream fileInputStream = new FileInputStream(message.getFile());
                FileOutputStream fileOutputStream = new FileOutputStream("D:\\ServerFiles\\"+time+"_"+message.getFile().getName());
                   
                FileChannel fis = fileInputStream.getChannel();
                FileChannel fout = fileOutputStream.getChannel();
                
                long size = fis.size();
                fis.transferTo(0, size, fout);
                
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("1");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("2");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
        }
        private void imprime(Arquivo message) {
            try {
                FileReader fileReader = new FileReader(message.getFile());
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                String linha;
                while((linha = bufferedReader.readLine()) != null){
                    System.out.print(linha);
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        }
    }
    
    public static void main(String[] args){
        try {
            new Client();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}

Parte do Erro:

[code]
private void salve(Arquivo message){

        try {
            
            Thread.sleep(new Random().nextInt(1000));
            
            long time = System.currentTimeMillis();
            
            FileInputStream fileInputStream = new FileInputStream(message.getFile());
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\ServerFiles\\"+time+"_"+message.getFile().getName());
               
            FileChannel fis = fileInputStream.getChannel();
            FileChannel fout = fileOutputStream.getChannel();
            
            long size = fis.size();
            fis.transferTo(0, size, fout);
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("1");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("2");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }[/code]

Existe esses diretorios ate o arquivo?

sim

vamos la

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.

me falta ver o codigo da classe Arquivo. se vc recebe isso pela rede a partir de um outro computador, eu imagino que, ao fazer getFile() vc recebe um objeto File que aponta para um arquivo local que vc não tem.

um File não é o conteudo do arquivo. vc tem que ler e enviar pelo stream de alguma forma ( talvez um array de bytes )

Tentei assim:
private void salve(Arquivo message) throws FileNotFoundException{

				FileOutputStream fileOutputStream = new FileOutputStream("D:\\ServerFiles\\"+message.getFile().getName());
			       
				
		}

O arquivo chega no outro pc e salva na pasta correta mais ele chega com 0 bytes

vc tem que ler o arquivo antes de enviar.

alias o que vc esta fazendo é algo “guloso” em relação a memoria. se vc tentar transferir algo muito grande vc vai ficar sem memoria primeiro.

eu tentaria utilizar um outro tipo de protocolo como HTTP ( que ja existem bibliotecas prontas ) ou criar um protocolo bem simples inspirado no HTTP como

filename: arquivo.txt
content-type: text/plain
size: 19999
md5: 475340857340587034

bytes em base64 ou binario

dessa forma vc só precisa ler 4 linhas que vai ter o header completo incluindo o nome do arquivo, o tamanho, o md5 se quiser verificar a integridade, um content-type ( que pode ser optional E util, no caso de vc receber bytes de um arquivo texto que pode estar em diferentes codificações como utf-8, latin-1, utf-16, etc )

sabendo do tamanho, vc sabe quanto vc precisa ler. se vc separar o body do header por uma linha em branco, fica muito simples vc ler e escrever em pequenas quantidades ( ao inves de ler tudo e gravar, vc pode ler 10k por vez ).

isso não é muito diferente do protocolo http.

perceba que o arquivo pode corromper por isso vc pode colocar um hash pra verificar.

1 curtida