Java 从servlet中的文本文件读取和写入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20728953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading and writing from text file in servlet
提问by Jawad Rauf
I want to write a string from my jsp page and store it in servlet. and if users enter the same string again servlet reads that string from the text file if it exist it tells the string is already been stored and if its not there it writes that string in text file.
我想从我的 jsp 页面写入一个字符串并将其存储在 servlet 中。如果用户再次输入相同的字符串,servlet 会从文本文件中读取该字符串(如果存在),它会告诉该字符串已经存储,如果不存在,则将该字符串写入文本文件中。
Here is my code of jsp where i am getting string called "starting bid price"
这是我的 jsp 代码,其中我收到名为“起始出价”的字符串
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="mona.java" method="POST">
Name:<input type="text" name="Name"><br>
Email:<input type="text" name="Email"><br>
Item Name:<input type="text" name="Item Name"><br>
Item Description:<input type="text" name="Item Description"><br>
Starting Bid Price:<input type="text" name="Starting bid Price"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Here is my code of servlet.
这是我的servlet代码。
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("Name");
String s2 = request.getParameter("Email");
String s3 = request.getParameter("Item Name");
String s4 = request.getParameter("Item Description");
String s5 = request.getParameter("Starting bid Price");
try{
File file = new File("c:/example/filedata.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String temp = bufferedReader.readLine();
while (temp != null) {
if(s5.equals(temp))
{
out.println("file already exist");
//fileReader.close();
}
else
{
PrintWriter fileWriter = new PrintWriter(new
FileOutputStream("c:/example/filedata.txt",true));
fileWriter.println( s5 );
out.println("file saved");
fileWriter.close();
}
fileReader.close();
}
}
catch(FileNotFoundException fnfe) {
}
finally{
}
}
采纳答案by Jiri Kusa
Your question is a bit unclear, but if I understand well, you only need to make this piece of code work.
你的问题有点不清楚,但如果我理解得很好,你只需要让这段代码工作。
Well, first problem is
嗯,第一个问题是
String temp = bufferedReader.readLine();
while (temp != null) {
Your code reads only first line from file, and if it is not null, you endlessly process the code in while loop.
您的代码仅从文件中读取第一行,如果它不为空,您将在 while 循环中无休止地处理代码。
Should be something like this:
应该是这样的:
String temp = null;
while ((temp = bufferedReader.readLine()) != null) {
// do your stuff here.
Another possible problem:
另一个可能的问题:
out.println("file already exist");
If this should print text on console, it should be
如果这应该在控制台上打印文本,它应该是
System.out.println("file already exist");
Suggestions: While processing resources such as File, you should close streams/readers in finally block, because if exception occurs before resource is closed, resource remains opened.
建议:在处理File等资源时,应该在finally块中关闭streams/readers,因为如果在资源关闭前发生异常,资源保持打开状态。
And one opinion at the end. I personally wouldn't place File processing in servlet, it should be placed in some business logic class. Then I would call from servlet first method to test, if file contains specific string, and if not, I would call another method, which would append new line to existing file.
最后还有一个意见。我个人不会把文件处理放在servlet中,它应该放在一些业务逻辑类中。然后我会从 servlet 第一个方法调用来测试,如果文件包含特定的字符串,如果没有,我会调用另一个方法,它将新行追加到现有文件中。
If you need something else not covered in my answer, please specify a bit more. Hope it helps.
如果您需要我的答案中未涵盖的其他内容,请指定更多内容。希望能帮助到你。
EditOne more thing I noticed. When you find match in your file, you should terminate the while loop (return or break), or even better, define boolean variable as false before loop, if you find your match in file, set it to true and break loop. After while loop ends, test if variable is true, if not, append your line to file (not in while loop).
编辑我注意到的另一件事。当您在文件中找到匹配项时,您应该终止 while 循环(返回或中断),或者更好的是,在循环之前将布尔变量定义为 false,如果您在文件中找到匹配项,请将其设置为 true 并中断循环。while 循环结束后,测试变量是否为真,如果不是,将您的行附加到文件中(不在 while 循环中)。
Edit2Yes, it is the problem I mentioned above.
Edit2是的,就是我上面提到的问题。
String temp = bufferedReader.readLine();
while (temp != null) {
If first line of file is not null, you'll process loop endlessly.
如果文件的第一行不为空,您将无休止地处理循环。
With modifying your code a little, I would suggest following:
通过稍微修改您的代码,我建议如下:
boolean found = false;
File file = new File("c:/example/filedata.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((temp = bufferedReader.readLine()) != null) {
if(s5.equals(temp)) {
System.out.println("file already exist");
found = true;
break;
}
}
if (!found){
PrintWriter fileWriter = new PrintWriter(new
FileOutputStream("c:/example/filedata.txt",true));
fileWriter.println( s5 );
System.out.println("file saved");
}
回答by Alaychem Remember Monica
use
用
HttpSession session= request.getSession();
session.setAttribute ("name", name);
in order to save data in the session, and:
为了在会话中保存数据,以及:
(String)session.getAttribute ("name");
to get it back
把它拿回来