我正在编写一个java服务器,并始终从浏览器中读取请求。例如,我在浏览器http://localhost:8080/C:\Users\1\Desktop\tur.txt
中阅读此请求。然后保存文件路径。然后我想将文件的内容打印到浏览器。例如,某些文字位于tur.txt
。
我正在使用另一个类中的方法。
以下是此类的代码:
public class FileReader {
BufferedReader in;
File DataFile;
public void Reader(String directory, PrintStream out) throws IOException {
try {
File stockInputFile = new File(directory);
File StockOutputFile = new File(directory);
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
int count;
if (new File(directory).isDirectory()) {
directory=directory.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n"+
"Location: /"+directory+"/\r\n\r\n");
out.close();
return;
}
// Open the file (may throw FileNotFoundException)
InputStream f=new FileInputStream(directory);
// Determine the MIME type and print HTTP header
String mimeType="text/plain";
if (directory.endsWith(".html") || directory.endsWith(".htm"))
mimeType="text/html";
else if (directory.endsWith(".jpg") || directory.endsWith(".jpeg"))
mimeType="image/jpeg";
else if (directory.endsWith(".gif"))
mimeType="image/gif";
else if (directory.endsWith(".txt"))
mimeType="text/txt";
else if (directory.endsWith(".class"))
mimeType="application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n"+
"Content-type: "+mimeType+"\r\n\r\n");
System.out.println(mimeType);
// Send file contents to client, then close the connection
byte[] a=new byte[4096];
int n;
while ((n=f.read(a))>0)
out.write(a, 0, n);
// out.flush();
out.close();
}
catch (FileNotFoundException x) {
out.println("HTTP/1.0 404 Not Found\r\n"+
"Content-type: text/html\r\n\r\n"+
"<html><head></head><body>"+directory+" not found</body></html>\n");
out.close();
}
}
}
它需要一个目录来查找磁盘上的文件和PrintStream(PrintStream out = new PrintStream(new BufferedOutputStream(serSock.getOutputStream()));
)以将内容打印到浏览器。但是,问题在于我读这个文件的时候。此文件的内容将删除。这意味着我在tur.txt
中删除的所有文本都已删除。并且文件变成了打印到浏览器的内容。
任何人都可以解释原因吗?谢谢。
答案 0 :(得分:0)
问题在于:
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
在FileOutputSteam中。因此,当我删除这两行时,程序开始正常工作。我忘记了FileOutputStream清除了文件中存储的所有数据。
我要感谢@lamsomeone的帮助。