In: Computer Science
I kept getting errors trying to make this code to work, can someone show me what i am doing wrong?
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.nio.charset.*;
import java.util.*;
//@WebServlet(name = "Assignment3_1", urlPatterns = { "/ReadFile"
})
public class ReadFile extends HttpServlet{
static Charset myCharset = Charset.forName("US-ASCII");
@Override public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
response.setContentType("text/html");
PrintWriter printer = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>");
out.println("Assignment 5.1");
out.println("</title>");
out.println("<h1>Is Bitcoin money?</h1>");
out.println("</head>");
out.println("<body>");
out.println("<div>");
writeAndReadFile(printer);
out.println("</div>");
out.println("</body>");
out.println("</html>");
}
private synchronized void writeAndReadFile(PrintWriter out){
try{
Path file = Paths.gets("C:/Temp/servlet1.dat");
List <String> linesReads = null;
// Read every line in the .dat file.
linesRead = Files.readAllLine(file, myCharset);
if(linesRead is null){
for(String line : linesRead){
out.println(line + "<br />\n");
}
}
}
catch(IOException e)
{
out.println("ERROR* >> "); out.println(e.toString());
}
}
}
/* WRONG STATEMENT IN YOUR CODE WAS */
wrong: PrintWriter printer = response.getWriter();
correct: PrintWriter out = response.getWriter(); // since you use out for println statement
wrong: writeAndReadFile(printer);
correct: writeAndReadFile(out);//PASS OUT
wrong: Path file = Paths.gets("C:/Temp/servlet1.dat");
correct : Path file = Paths.get("C:/Temp/servlet1.dat");//get is method
wrong: linesRead = Files.readAllLine(file, myCharset);
correct: linesReads = Files.readAllLine(file, myCharset); // since you create variable linesReads
if(linesReads == null){
for(String line : linesReads){
out.println(line + "<br />\n");
/* Match your code from Screenshot */
/* OUTPUT */
/* SINCE I HAVE NO FILE SERVER1.DAT */
/* PLEASE UPVOTE */