我是Socket编程的新手。我试图在服务器上写一个文件,但我的代码抛出异常:
java.io.FileNotFoundException: Welcome-PC\IndiraSharing\hadoop.txt (The system cannot find the path specified)
这是我的代码。
Socket s;
ServerSocket server = new ServerSocket(5555);
String serveradd;
serveradd=s.getInetAddress().getHostName();
// System.out.println("Server accepted client");
InputStream input = s.getInputStream();
BufferedReader inReader = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String filename = inReader.readLine();
if ( !filename.equals("") ){
outReader.write("READY\n");
outReader.flush();
}
FileOutputStream wr = new FileOutputStream(new File(serveradd+"\\IndiraSharing/" + filename));
byte[] buffer = new byte[s.getReceiveBufferSize()];
int bytesReceived = 0;
while((bytesReceived = input.read(buffer))>0)
{
wr.write(buffer,0,bytesReceived);
}
答案 0 :(得分:2)
找不到目录。该消息令人困惑,因为它涉及“文件”,但在Java IO中,目录也是文件。
如果你跑:
File dir = new File(serveradd+"\\IndiraSharing")
System.out.println(dir.exists());
它将打印:
false
您可以尝试创建目录结构:
dir.mkdirs();
另外,检查绝对路径是否符合预期:
System.out.println(dir.getAbsolutePath());
答案 1 :(得分:0)
Welcome-PC\IndiraSharing\hadoop.txt
是一个相对路径,我确定你应该为套接字程序指定一个绝对路径。顺便说一句,即使你想创建一个新文件,该目录也应该存在。