Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 25th, 2012  |  syntax: None  |  size: 1.74 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Reading a field in a line divided by tabs
  2. a | b | c(may contain url) | d(may contain url)
  3.        
  4. package eu.webfarmr.stackoverflow;
  5.  
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.FileNotFoundException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.Scanner;
  12.  
  13. /**
  14.  * The goal of this class is to read lines from a text file which contain
  15.  * vertical bars and extract the fields separated by these tabs
  16.  *
  17.  * @author djob
  18.  *
  19.  */
  20. public class FileLACSReader {
  21.  
  22.     private final static String SEPARATOR = "\|";
  23.  
  24.     /**
  25.      *
  26.      * @param args
  27.      */
  28.     public static void main(String args[]) throws Exception{
  29.         List<String> lines = readContents("etc/sampleInput.txt");
  30.         for (String input : lines) {
  31.             String[] splitContent = input.split(SEPARATOR);
  32.             for (String field : splitContent) {
  33.                 System.out.println(field);
  34.             }
  35.         }
  36.     }
  37.  
  38.     public static List<String> readContents(String file)
  39.             throws FileNotFoundException {
  40.         List<String> textLines = new ArrayList<String>();
  41.         FileInputStream stream = new FileInputStream(new File(file));
  42.         Scanner scanner = new Scanner(stream);
  43.         try {
  44.             while (scanner.hasNextLine()) {
  45.                 textLines.add(scanner.nextLine());
  46.             }
  47.         } finally {
  48.             scanner.close();
  49.         }
  50.         return textLines;
  51.  
  52.     }
  53.  
  54. }
  55.        
  56. String line = "a | b | c(may contain url) | d(may contain url)";
  57.     String[] parts = line.split("\|");
  58.     String lastPart = parts[parts.length - 1];
  59.     System.out.println(lastPart);
  60.        
  61. String str = "a | b | c(may contain url) | d(may contain url)";
  62. int x = str.lastIndexOf("|");
  63. String str1 = str.substring(x+2);
  64. System.out.println(str1);