Is java's File class' object serializable?

自闭症网瘾萝莉.ら 提交于 2019-12-23 19:14:45

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/25073435/is-javas-file-class-object-serializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!