简要说明:
我的应用程序将文件从服务器端发送到客户端,客户端选择文件名和扩展名,但是为了让客户端看到文件列表,我编写了一个列出文件的方法在服务器上可用。
虽然该方法有效,但我需要将文件名发送到客户端并将它们插入 JPanel
并在那里列出它们,以便用户可以选择他想要的文件。
这是我在服务器端的方法:
public static void listfile() {
String path = "C:/SAVE";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
}
我如何修改它以便它在调用时将文件列表发送给客户端。
最佳答案
如果您使用的是 tcp 连接,您的服务器可以执行一个名为“listFiles”的命令。当它收到这个命令时,它应该向客户端发送文件列表。
客户端应连接到服务器,发送命令“listFiles”,读取服务器发送的文件列表并将其显示在其JPanel 上。
假设您有一个采用以下模式的简单单线程服务器:
class Server
{
public void run()
{
ServerSocket server = new ServerSocket(<portno>);
Socket socket = server.accept();
InputStream in = socket.getInputStream(); // for reading the command
OutputStream out = socket.getOutputStream(); // for writing out the list
// Now read the argument from in, say the result is in variable "cmd"
if("listFiles".equals(cmd))
{
// invoke your list files logic, and instead of writing to the console
// write it to out
}
}
}
您的客户端应遵循以下模式:
class Client
{
public void getList()
{
Socket client = new Socket(<portno>);
InputStream in = client.getInputStream(); // to read in the file list
OutputStream out = client.getOutputStream(); // to send the listFiles command
// Write the listFiles command to out
// Read in the list of files from in
// Update your JPanel with the list
}
}
我省略了从套接字读取和向套接字写入的实际操作,但您会明白的。
关于java - 将文件列表从服务器发送到客户端的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14319911/