从文件中读取?

时间:2012-11-16 12:53:34

标签: java servlets

请帮我做这样的事情,假设我们有一个文本文件 test.txt ,与此类似:

hello hello hello
<link1>http://stackoverflow.com<link1>

第一行文字,第二个链接包含在<link1>中。我按如下方式打印文件的内容:

 if(myName.equals(name)){

                        InputStreamReader reader  = null;
                        try{


                            File file =  new File("C:\\Users\\ваня\\Desktop\\asksearch\\" + list[i]);

                            reader =  new InputStreamReader(new FileInputStream(file), "UTF-8");

                            int b;

                            PrintWriter wr =   response.getWriter();
                            wr.print("<html>");
                            wr.print("<head>");
                            wr.print("<title>HelloWorld</title>");
                            wr.print("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
                            wr.print("<body>");
                            wr.write("<div>");
                            while((b = reader.read()) != -1) {
                                wr.write((char) b );
                            }
                            wr.write("</div>");
                            wr.write("<hr>");
                            wr.print("</body>");
                            wr.print("</html>");
                            wr.close();


                        }

只是一段代码:

while((b = reader.read()) != -1) {
   writer.write((char) b);
}

您希望分别显示文件本身的第一行和文件的第二行

PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
// then the first line
writer.write("</div>");
writer.write("<div>");
// then the second line
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");

2 个答案:

答案 0 :(得分:1)

为您的文件创建BufferedReader

File file = new File("test.txt");
BufferedReader br =  new BufferedReader(new InputStreamReader(
                         new FileInputStream(file), "UTF8"));

使用readLine方法读取一行(第一行):

PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
// here to display the text
writer.write(br.readLine());//this will read the first line
writer.write("</div>");

//And for the second line 

writer.write("<div>");
// here to display the text
writer.write(br.readLine());//this will read the next line i.e. second line
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");

希望这有帮助。

答案 1 :(得分:1)

我建议远离InputStreamReader作为您使用方法的编程类型,并使用Scanner或BufferedReader代替......每个方法都有一次读取一行的方法:

Scanner in = new Scanner(file);
String line = in.nextLine();

BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();