javadatainputstreamdataoutputstream

Write data from datainputstream to a file in Java


I am learning about socket programming in Java from the below link: https://www.geeksforgeeks.org/socket-programming-in-java/

The code for server from the tutorial is as follows(I have added extra lines to copy in a file):

// A Java program for a Server 
import java.net.*; 
import java.io.*; 

public class Server 
{ 
    //initialize socket and input stream 
    private Socket          socket   = null; 
    private ServerSocket    server   = null; 
    private DataInputStream in       =  null; 
    FileWriter fw;

    // constructor with port 
    public Server(int port) 
    { 
        // starts server and waits for a connection 
        try
        { 
            server = new ServerSocket(port); 
            System.out.println("Server started"); 

            System.out.println("Waiting for a client ..."); 

            socket = server.accept(); 
            System.out.println("Client accepted"); 

            // takes input from the client socket 
            in = new DataInputStream( 
                new BufferedInputStream(socket.getInputStream())); 

            String line = ""; 

            // reads message from client until "Over" is sent 
            while (!line.equals("Over")) 
            { 
                try
                { 
                    line = in.readUTF(); 
                    fw = new FileWriter("out.txt");
                    fw.write(line);
                    System.out.println(line); 

                } 
                catch(IOException i) 
                { 
                    System.out.println(i); 
                } 
            } 
            System.out.println("Closing connection"); 
            fw.close();
            // close connection 
            socket.close(); 
            in.close(); 
        } 
        catch(IOException i) 
        { 
            System.out.println(i); 
        } 
    } 

    public static void main(String args[]) 
    { 
        Server server = new Server(5000); 
    } 
} 

I have added extra lines in this code for filewriter where I create a file with name out.txt and copy the contents of the datainputstream into the file. But only when I type Over, the word Over is copied into the file and not any of the other content. What am I doing wrong here?


Solution

  • What am I doing wrong here?

    You're creating a new File again every time you're reading a line.

    Create one File, once at the beginning, and write your lines to it.