2012-03-27 6 views
-1

Je lis une ligne par le lecteur de tampon dans Java. La ligne est: abc 3.8229 1.0326 1 1 1.1386 1.006Java Buffer to string array

Comment puis-je stocker chaque mot de cette ligne dans un tableau de chaînes?

+2

définir un «mot» –

Répondre

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

En supposant que vous avez

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

Vous pouvez produire un tableau de chaînes en utilisant String.split().

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

Cela produirait un tableau contenant arr chaque mot de var.

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

Je suggère d'utiliser un scanner.

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

Du côté positif de cela, vous pouvez également utiliser les méthodes pratiques de

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

And its ilk.

0

Vous pouvez diviser les mots pendant que vous lisez de la mémoire tampon:

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(); 
    }