Split a string using Scanner class : Scanner « File Input Output « Java






Split a string using Scanner class

 
 
import java.io.File;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("data.txt");
    Scanner scanner = new Scanner(file);
    while (scanner.hasNextLine()) {
      String line = scanner.nextLine();

      Scanner lineScanner = new Scanner(line);
      lineScanner.useDelimiter(",");
      while (lineScanner.hasNext()) {
        String part = lineScanner.next();
        System.out.print(part + ", ");
      }
      System.out.println();
    }
  }
}

   
  








Related examples in the same category

1.new Scanner(new BufferedReader(new FileReader("xanadu.txt")))
2.Read file using Scanner class
3.Read user input from console using Scanner class
4.Scanning text with java.util.Scanner
5.Simplify the code in TextReader by using java.util.Scanner
6.Read in the current contents of the java.net homepage
7.Perform the conversions after parsing the String