dirthread.java
来自「java编程开发技巧与实例的编译测试通过的所有例程」· Java 代码 · 共 118 行
JAVA
118 行
import java.util.*;
import java.io.*;
import java.net.*;
public class DirThread extends Thread
{
private ObjectOutputStream out = null;
private DataInputStream in = null;
private Socket sock = null;
private boolean running = false;
private File currentPath = new File(System.getProperty("user.dir"));
public DirThread(Socket _sock)
{
System.out.println("Start directory connection . . . ");
sock = _sock;
try
{
in = new DataInputStream(sock.getInputStream());
out = new ObjectOutputStream(sock.getOutputStream());
running = true;
start();
}
catch (IOException ioe)
{
System.err.println("Error setting up streams: " + ioe);
}
}
public void run()
{
authenticate();
while (running)
{
try
{
processCommand(in.readUTF(),in.readUTF());
}
catch (IOException ioe)
{
hangup();
}
}
}
private void send(File list[]) throws IOException
{
FileInfo info[] = new FileInfo[list.length];
for (int i = 0; i < list.length; i ++)
info[i] = new FileInfo(list[i]);
out.writeObject(list);
out.flush();
}
private void send(String msg) throws IOException
{
out.writeUTF(msg);
out.flush();
}
private void changeDirectory(String newDir) throws IOException
{
if ((newDir.equals("..")) &&
(currentPath.getParentFile() != null))
currentPath = currentPath.getParentFile();
else
{
File newPath = new File(newDir);
if (newPath.exists() && newPath.isDirectory())
currentPath = newPath;
}
send(currentPath.toString());
}
private void authenticate()
{
try
{
String cmd = in.readUTF();
String passwd = in.readUTF();
if (passwd.equals(DirServer.VERSION + "|" + DirServer.PASSWD))
send("okay");
else
{
send("error");
hangup();
}
}
catch (IOException ioe)
{
hangup();
}
}
private void hangup()
{
try
{
System.out.println("Hanging up");
in.close();
out.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println("Error disconnecting: " + ioe);
}
finally
{
running = false;
}
}
private void processCommand(String cmd, String option) throws IOException
{
if (cmd.equals("pwd"))
send(currentPath.toString());
else if (cmd.equals("chdir"))
changeDirectory(option);
else if (cmd.equals("list"))
send(currentPath.listFiles());
else
hangup();
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?