我正在一个项目上,它需要将目录信息从一个客户端发送到网络上的另一个客户端.所以告诉我,我可以仅通过发送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类的对象可序列化吗?
发布评论