Domanda

Sorry to drag this up but I have had a good look around and I still keep getting an EOFException. I've commented everything out of my method apart from:

    File receivedFileObject;
    File newFile = new File("newlyWrittenFile.mp3");


    try{
        Socket socket = new Socket(SERVER_IP, PORT);

        try{
        ObjectInputStream incommingData = new ObjectInputStream(socket.getInputStream());

All I'm trying to do is pass a file, txt or mp3 from the server to the client - I don't even try to call readObject() on the ObjectInputStream and yet I still get EOFException? How can I reach the end of a file I haven't tried to read? In actual fact I wish I was trying to read a text file line by line, because I know how to do that perfectly fine. I just want to receive an Object, cast it to a file and write it to the file system but for some reason my catch block :

        } catch (IOException e){
            System.out.println("Incomming data assignment error : " + e);   
        }

prints out :

Incomming data assignment error : java.io.EOFException

I have been trying to follow along with the server code listed in this forum post. Basically from the server I use the following lines to write the file to the client:

        if (myFile.exists()) {
        ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());

        oos.writeObject(myFile);
    }

I would be really grateful if someone could explain how to fix what feels like a stupid error on my part - Thanks in advance!

È stato utile?

Soluzione

An ObjectOutputStream is used for serializing a java object to a stream. It is unlikely that you want to do this.

If you want to "pass a file", that probably means you want to "pass the contents of the file", so just to this:

FileOutputStream newFile = new FileOutputStream("newlyWrittenFile.mp3");
InputStream input = socket.getInputStream();
byte[] bytes = // pseudo code for reading all bytes from input
newFile.write(bytes); // pseudo code for writing to file
newFile.close();

You might find apache common-io library IOUtils class methods quite handy to read and write your data easily

Altri suggerimenti

If you check the javadoc of ObjectInputStream:

A serialization stream header is read from the stream and verified.

So creating the object does trigger a read.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top