Home Segments Top Top Previous Next

485: Mainline

Now, you combine trim, indexOf, substring and parseInt to read three successive numbers from each line of text:

import java.io.*;
public class Demonstrate {
 public static void main(String argv[]) throws IOException {
  FileInputStream stream = new FileInputStream("input.data");
  InputStreamReader reader = new InputStreamReader(stream);
  BufferedReader buffer = new BufferedReader(reader);
  String line;
  while ((line = buffer.readLine()) != null && !line.equals("")) {
   line = line.trim();                                          
   int nextSpace = line.indexOf(" ");                           
   int x = Integer.parseInt(line.substring(0, nextSpace));      
   line = line.substring(nextSpace).trim();                     
   nextSpace = line.indexOf(" ");                               
   int y = Integer.parseInt(line.substring(0, nextSpace));      
   line = line.substring(nextSpace).trim();                     
   int z = Integer.parseInt(line);                              
   System.out.println("Numbers read: " + x + ", " + y + ", " + z);  
  } 
  stream.close(); 
  return; 
 } 
} 
--- Data ---
 4  7  3 
 8  8  7 
 2 10  5 
--- Result --- 
Numbers read: 4, 7, 3 
Numbers read: 8, 8, 7 
Numbers read: 2, 10, 5