Java的File类的对象可序列化吗?

编程入门 行业动态 更新时间:2024-10-10 17:31:48
本文介绍了Java的File类的对象可序列化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在一个项目上,它需要将目录信息从一个客户端发送到网络上的另一个客户端.所以告诉我,我可以仅通过发送File类的对象来在另一个客户端上获得此信息吗?请向我解释您选择是或否的原因.

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.

更新的问题

我正在发布我尝试过的代码....

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

客户代码:-

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

以下是服务器代码:-

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

如果我在本地主机上运行服务器,这很好用,但是当我使用两台不同的机器时,其中一台用于客户端,另一台用于服务器,则输出是不同的(显示0字节读取).这似乎是正确的,因为实际文件在远程服务器上不可用.我对File class的字段感到困惑,即

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

读取File对象后,服务器将获得什么确切的信息?

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

推荐答案

是的,您可以使用File类引用发送信息,因为它实现了Serializable接口.

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

有关更多详细信息,请阅读Java的File API参考.

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

您可以通过以下代码来实现:

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

更多推荐

Java的File类的对象可序列化吗?

本文发布于:2023-11-11 08:50:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577941.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   序列化   Java   File

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!