1

从我的客户端类中,我将发送一个用于文件名的字符串,一个用于内容的字符串。

在服务器上,如何根据从客户端收到的字符串创建文件?

客户端类:

 String theFile = "TextDoc.txt";
 String theFileContent = "text inside TextDoc";

 sendToServer.writeBytes(theFile +"\n");
 sendToServer.writeBytes(theFileContent);

服务器类:

 BufferedReader reFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

 String theFileFrCl = reFromClient.readLine();
 String theFileCtFrCl = reFromClient.readLine();

如何根据客户发送的内容制作文件?我不太确定如何将内容附加到 TextDoc。

马丁。

4

1 回答 1

1

在服务器端,我们收到了文件名和内容:

 BufferedReader reFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

 String theFileFrCl = reFromClient.readLine(); // file name.
 String theFileCtFrCl = reFromClient.readLine(); // contents.

在此之后,我们将编写文件:

FileOutputStream fos = new FileOutputStream(theFileFrCl,true); // opening file in append mode, if it doesn't exist it'll create one.
fos.write(theFileCtFrCl.getBytes()); // write contents to file TextDoc.txt
fos.close();

如果您想将某些文件的内容返回给客户端,只需像以前一样从客户端请求文件名:

theFileFrCl = reFromClient.readLine(); // client will write and we'll read line here (file-name).

现在只需使用收到的文件名打开文件:

try{
  FileInputStream fis = new FileInputStream(theFileFrCl);
  byte data[] = new byte[fis.available()];
  fis.read(data);
  fis.close();
  toClient.writeBytes(data); // write to client.
}catch(FileNotFoundException fnf)
{
  // File doesn't exists with name supplied by client 
}
于 2013-03-20T17:58:02.473 回答