【发布时间】:2015-08-29 21:38:49
【问题描述】:
我还有一个问题。现在我正在编写一个小程序,它可以在我的电脑和笔记本电脑上运行。这两个程序相互通信。我可以写字符串(比如聊天),我想发送文件。这个小聊天有效,但文件现在出现问题。这让我有点疑惑,因为几天前我已经开始运行它了。但现在它不起作用(不记得我改变了重要的事情)。不幸的是,我无法撤消,因为 Eclipse 已经关闭。
所以我一直在寻找错误,但几个小时以来我一直找不到它。我希望你能帮助我。
情况:
我在我的电脑/笔记本电脑上选择一个文件并将其发送到我的笔记本电脑/电脑(我以与文件相同的方式发送文本 [Strings] 并且它可以工作)。接收方应将文件保存在一个目录中(targetPath - 它在代码中的其他位置定义。它是我桌面上的一个文件夹)。所以我从“ObjectInputStream”获取文件作为对象并将其转换为“文件”:
if(msg instanceof File){ //msg is the object I got from the ObjectInputStream
//its a file
model.copyFileTo((File) msg);
}
这就是麻烦的方法:
public void copyFileTo(File file) throws IOException{
System.out.println(file.getName());//this is just a test and it works. It prints out the name of the sended file
if(targetPath.toFile().exists()){
if(file.exists()){
Path temp = Paths.get(targetPath+"/"+file.getName());
if(!temp.toFile().exists()){
Files.copy( file.toPath(), temp, StandardCopyOption.REPLACE_EXISTING);
System.out.println("copied");
}else{
System.out.println("File already exists");
}
}else{
System.out.println("File doesnt exists");
}
}else{
System.out.println("targetPath doesnt exists!");
}
}
我没有出错,但它会打印“文件不存在”,所以“if(file.exists())”处的某些内容出错了。如果我把这部分剪掉,程序会挂在 Files.copy(...) 处,我知道这是因为它不会打印出“已复制”。
【问题讨论】:
-
"所以我从
ObjectInputStream获取文件作为对象并将其转换为File": Cast???无需铸造。对象输入流???你为什么要用那个? ---File代表文件的名称,而不是内容,只需使用普通的InputStream来读取字节。 -
我想我必须强制转换它,因为当我想将它保存在一个目录中时,我需要它作为文件。
-
ObjectInputStream用于反序列化 Java 对象,很少使用。 ---File对象包含文件的名称。文件的内容是byte数组(如果是二进制)或String(如果是文本)。 -
但是当我想将它保存在目录“Files.copy(file.toPath(), temp, StandardCopyOption.REPLACE_EXISTING);”中时,我需要它作为文件/路径。所以我在从 InputStream 中得到它之后再转换它。这是错的吗?
标签: java file-io objectinputstream