Java基础篇之如何读取字符串

1,466 阅读1分钟

上一篇文章中讲述了如何读取字符,本篇就说说如何读取字符串。从键盘读取字符串,使用readLine()。它是BufferedReader 类的成员。它的通常形式如下:

String readLine( ) throws IOException

它返回一个String对象。

下面的例子阐述了BufferedReader类和readLine()方法;程序读取和显示文本的行直到键入“stop”:

// Read a string from console using a BufferedReader. 
import java.io.*; 
class BRReadLines { 
 public static void main(String args[]) 
 throws IOException 
 { 
 // create a BufferedReader using System.in 
 BufferedReader br = new BufferedReader(new 
 InputStreamReader(System.in)); 
 String str; 
 System.out.println("Enter lines of text."); 
 System.out.println("Enter 'stop' to quit."); 
 do { 
 str = br.readLine(); 
 System.out.println(str); 
 } while(!str.equals("stop")); 
 } 
}

下面的例题生成了一个小文本编辑器。它创建了一个String对象的数组,然后依行读取文本,把文本每一行存入数组。它将读取到100行或直到你按“stop”才停止。该例运用一个BufferedReader类来从控制台读取数据。

// A tiny editor. 
import java.io.*; 
class TinyEdit { 
 public static void main(String args[]) 
 throws IOException 
 { 
 // create a BufferedReader using System.in 
 BufferedReader br = new BufferedReader(new 
 InputStreamReader(System.in)); 
 String str[] = new String[100]; 
 System.out.println("Enter lines of text."); 
 System.out.println("Enter 'stop' to quit."); 
 for(int i=0; i<100; i++) { 
 str[i] = br.readLine(); 
 if(str[i].equals("stop")) break; 
 } 
 System.out.println("\nHere is your file:"); 
 // display the lines 
 for(int i=0; i<100; i++) { 
 if(str[i].equals("stop")) break; 
 System.out.println(str[i]); 
 } 
 } 
}

下面是输出部分:

Enter lines of text. 
Enter ‘stop’ to quit. 
This is line one. 
This is line two. 
Java makes working with strings easy. 
Just create String objects. 
stop 
Here is your file: 
This is line one. 
This is line two. 
Java makes working with strings easy. 
Just create String objects.