2012-11-16 119 views
0

請幫我做這樣的事情,讓我們說我們有一個文本文件,的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>"); 
+1

這就是所謂的「編程」你存儲線字符串,另一個在另一個字符串。爲了分隔行,最好使用'BufferedReader',它提供'readLine'方法。 – SJuan76

+0

你能展示一段代碼嗎 –

+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>"); 

希望這有助於。

+0

謝謝,但那裏我編碼UTF_8,並且你沒有它在這裏 –

+0

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

+0

@EricScot看到我編輯的代碼爲UTF-8文件 – Abubakkar

1

我建議您將InputStreamReader作爲一種編程類型使用,您可以使用Scanner或BufferedReader,而不是使用Scanner或BufferedReader ...每種方法都有一次讀取一行的方法:

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

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