Advertisement
Guest User

Untitled

a guest
Apr 27th, 2015
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4.  
  5. public class RowDelimitedFileExample {
  6.  
  7. private static final String INPUT_FILE = "C:/workspace/Sample.csv";
  8. private static final String ROW_DELIMITED_BY = "\n";
  9. private static final String FIELD_DELIMITED_BY = ",";
  10.  
  11. public static void main(String[] args) {
  12.  
  13. // Creating the file object
  14. File aFile = new File(INPUT_FILE);
  15.  
  16. // Creating the variable of type Scanner
  17. Scanner theScanner = null;
  18.  
  19. try {
  20. // Creating the scanner to read the lines in the ROW_DELIMITED file
  21. theScanner = new Scanner(aFile).useDelimiter(ROW_DELIMITED_BY);
  22.  
  23. // Iterating through the ROWS
  24. while (theScanner.hasNext()) {
  25.  
  26. String row = theScanner.next();
  27.  
  28. // Splitting the ROW into Fields based on the FIELD_DELIMITER
  29. for (String field : row.split(FIELD_DELIMITED_BY)) {
  30.  
  31. // Printing the FIELDS contents
  32. System.out.printf("%s|", field.trim());
  33.  
  34. }
  35. // Printing a New-line
  36. System.out.print(System.lineSeparator());
  37. }
  38.  
  39. // Catching the FileNotFound Exception
  40. } catch (FileNotFoundException e) {
  41.  
  42. // Handling the Exception condition
  43. System.err.println("The file [" + INPUT_FILE + "] is not found !");
  44.  
  45. } finally {
  46.  
  47. // Handling closing of open resources
  48. theScanner.close();
  49. }
  50.  
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement