我正在尝试用 java 构建我的简单网络服务器。所以我在教程中找到了这段代码,
我试图理解这种方法的作用,但我无法解释 BufferedReader 的用途以及他为什么使用它。
public void run()
{
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = reader.readLine();
String filename = "";
File file = null;
String parts[] = line.split(" ");
if (parts.length != 3)
{
return;
}
if (parts[0].compareTo("GET") == 0)
{
filename = parts[1].substring(1);
if (filename.equals("favicon.ico") == true)
{
System.out.println("404 File Not Found!");
return;
}
else
{
System.out.println(filename);
}
}
printToBrowser(bos, "HTTP/1.1 200 OK");
printToBrowser(bos, "");
if (filename.compareTo("") == 0)
{
file = new File("index.txt");
}
else
{
file = new File(filename);
}
try
{
FileInputStream input = new FileInputStream(file);
int a;
byte[] buffer = new byte[1024];
while ((a = input.read(buffer, 0, 1024)) > 0)
{
sleep(100);
bos.write(buffer, 0, a);
}
}
}