java文件读取器删除文件的内容
我正在编写一个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
中删除的所有文本。文件将被打印到浏览器中
有人能解释为什么吗?谢谢
# 1 楼答案
问题就在这里:
在蒸汽中。因此,当我删除这两行时,程序开始正常工作。我忘了FileOutputStream会清除文件中存储的所有数据
我想感谢某人的帮助