2012-03-27 102 views
-1

我正在通过java中的缓冲区读取器读取一行。 行是: abc 3.8229 1.0326 1 1 1.1386 1.006Java缓冲区到字符串数组

如何将此行的每个单词存储在字符串数组中?

+2

定义一个“字” – 2012-03-27 11:31:44

回答

0
import java.io.*; 
    class Record 
    { 
    String name; 
    String s1; 
    String s2; 
    String s3; 
    String s4; 
    String s5; 
    String s6; 

    public Record(String name, String s1, String s2, String s3, String s4, String s5, String s6){ 
    this.name = name; 
    this.s1 = s1; 
    this.s2 = s2; 
    this.s3 = s3; 
    this.s4 = s4; 
    this.s5 = s5; 
    this.s6 = s6; 

}

public static void main(String args[]){ 
    try{ 
    FileInputStream fstream = new FileInputStream("textfile.txt"); 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String strLine; 
     while ((strLine = br.readLine()) != null) { 
    String[] tokens = str.split(" "); 
    Record record = new Record(tokens[0],tokens[1],tokens[2],tokens[3],tokens[4],tokens[5],tokens[6]);//process record , etc 

} 
in.close(); 
    }catch (Exception e){ 
    System.err.println("Error: " + e.getMessage()); 
} 
    } 
    } 
6

假设你有

String var = "abc 3.8229 1.0326 1 1 1.1386 1.006"; 

你可以使用产生一个String.split() String数组。

String[] arr = var.split(" "); 

这将产生含有var每个字的阵列arr

3
BufferReader br; 
... 
String line = br.readLine(); 
String[] words = line.split(" "); 
1

我建议使用扫描仪。

Scanner sc = new Scanner(line); 
while(sc.hasNext()){ 
    String word = sc.next(); // Get word 
} 

在此有利的一面,你也可以使用的

double x = sc.nextDouble(); 
int i = sc.nextInt(); 

And its ilk.

0

便捷的方法,您可以在您从缓冲区中读取分裂的话:

try { 
     String line = "abc 3.8229 1.0326 1 1 1.1386 1.006"; 
     List newWordSymbols = Arrays.asList(' ','\n','\r'); 


     StringReader sr = new StringReader(line); 
     List wordList = new ArrayList(); 
     StringBuilder word = new StringBuilder(); 
     int ch; 
     while ((ch=sr.read())!=-1) {  
      char c = (char)ch; 

      if(newWordSymbols.contains(c)){ 
       wordList.add(word.toString()); 

       word= new StringBuilder(); 
      }else{ 
       word.append(c); 
      } 

     } 
     wordList.add(word.toString()); 


     System.out.println("Word list ::: "+wordList); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    }