I, the following servlet code does not display the characters, place them, he says something like this:  ршншнщ олрршш. Could you help fix it, I will be very grateful, I beginner in java so you can please send me the code to encoded everything was fine, it is advised to use:
.getBytes("UTF-8");
Here’s the code:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<String> getFileNames(File directory, String extension) {
List<String> list = new ArrayList<String>();
File[] total = directory.listFiles();
for (File file : total) {
if (file.getName().endsWith(extension)) {
list.add(file.getName());
}
if (file.isDirectory()) {
List<String> tempList = getFileNames(file, extension);
list.addAll(tempList);
}
}
return list;
}
@SuppressWarnings("resource")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf8");
response.setContentType("text/html; charset=UTF-8");
String myName = request.getParameter("text");
List<String> files = getFileNames(new File("C:\\Users\\vany\\Desktop\\test"), "txt");
for (String string : files) {
if (myName.equals(string)) {
try {
File file = new File("C:\\Users\\vany\\Desktop\\test\\" + string);
FileReader reader = new FileReader(file);
int b;
PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
while((b = reader.read()) != -1) {
writer.write((char) b);
}
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");
}
catch (Exception ex) {
}
}
}
}
}
all I solved the problem, close all the giant question thanks.Special thanks to @BalusC put him pluses)
This problem is two-fold.
First, you forgot to set the response encoding. This way the response is written with server platform default encoding. Add the following line before writing any byte/character to the response.
Second, you’re reading the file using server platform default encoding.
You should be reading the file using an explicitly specified encoding matching the encoding actually used by the text file itself. This can be done with help of
InputStreamReader.See also:
Unrelated to the concrete problem, HTML code doesn’t belong in a servlet. It belongs in a JSP. Continue here to learn how to deal with it: Generate an HTML Response in a Java Servlet.