Anubhav
Anubhav

Reputation: 103

Is java's File class' object serializable?

I am working on a project, it requires to send directory information from one client to another on a network. so tell me, can i get this information on another client by only sending File class' object? please explain me the reason for your YES or NO.

Updated Question

i am posting the code which i have tried....

The Client Code:-

public class FileClient{
    public static void main(String str[]){
        try{
            Socket sock = new Socket("10.16.10.82",4000);

                    /* Socket sock = new Socket("127.0.0.1",4000); */ //for localhost 
            File f = new File("MyFile.txt");
            ObjectOutputStream os = new ObjectOutputStream(sock.getOutputStream());
            os.writeObject(f);
            os.flush();
            os.close();
            System.out.println("object sent");
        }
        catch(Exception ex){
            ex.printStackTrace();

        }

    }
}

And The following is the server code:-

class FileServer{
    public static void main(String str[]){
        try{
            ServerSocket sock = new ServerSocket(4000);
            while(true){
                Socket cs = sock.accept();
                ObjectInputStream in = new ObjectInputStream(cs.getInputStream());
                File f = (File)in.readObject();
                System.out.println(f.isDirectory());
                System.out.println(f.length()+" bytes read");
            }
        }
        catch(Exception ex){
            ex.printStackTrace();

        }

    }
}

this works fine if i run server on localhost but when i use two different machines one for client and other for server the output is different (it shows 0 bytes read). it seems right because the actual file is not available at remote server. i am confused about File class' field i.e.,

static private FileSystem fs = FileSystem.getFileSystem() //see javadoc for File

what exact information server is getting after reading the File object?

Upvotes: 6

Views: 6909

Answers (1)

jcool
jcool

Reputation: 324

Yes you can send information using the File class reference because it implements the Serializable interface.

For more details, read Java's File API reference.

Code example

You can achieve it by following code:

String sourcePathFilename = "path.txt";
try {
    File file = new File(sourcePathFilename);
    FileOutputStream fos = new FileOutputStream(String targetpath);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(file);
} catch (Exception e) {
    e.printStackTrace();
}

Upvotes: 3

Related Questions