0

I'm trying to create a simple Client-Server java program. Simple, I need to send a text file (ToSend.txt) from the Server to the client, it's in the same directory where the Server.java is. After running the program, the ToSend.txt file should be in the same directory where the Client.java is, and will be renamed as Received.txt.

Server:

File file = new File("ToSend.txt");

try
{
    ServerSocket serverSocket = new ServerSocket(1234);
    Socket serverEndpoint = serverSocket.accept();

    //what to do here?

    serverEndpoint.close();
}
catch (Exception e)
{
    e.printStackTrace();
}

Client:

try
{
     Socket clientEndpoint = new Socket(localhost, 1234);

     //what to do here?

     clientEndpoint.close();
}
catch (Exception e)
{
    e.printStackTrace();
}

ToSend.txt

Self-learning during a global pandemic is difficult.

I got confused if I will use DataOutputStream or just OutputStream or FileReader, i need help.

  • There you go, https://stackoverflow.com/questions/9520911/java-sending-and-receiving-file-byte-over-sockets. It shows you how to create a Server and a Client and how to send a file. – JCompetence Dec 01 '20 at 18:12
  • `File` is an abstract representation of a file - it doesn't have a reference to the actual content. Use a `FileInputSteam` or `FileReader` to read the contents of the file, then send the contents via the output stream (which you can wrap in `DataOutputStream` for simplicity) – Vince Dec 01 '20 at 18:14
  • For a text file, you want a Reader/Writer. I tend to use BufferedWriter or BufferedReader for this sort of thing. The Reader/Writer is designed for text streaming. – NomadMaker Dec 01 '20 at 18:49

1 Answers1

0

First you need to serialize the file then send it, you can't just send a file like that, this has been already answered, so I will not repeat the answer, I will just link an answer other user provided.

Java sending and receiving file (byte[]) over sockets

Try looking up videos how to serialize data in java there are different methods, using bytes like the one linked, this is part of the Java streams tutorial and it is very useful to learn how streams actually operate.

mssp
  • 16
  • 5