Advertisement
katiek

NiceFile

Dec 21st, 2011
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.29 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileReader;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.util.ArrayList;
  7. import nice.core.fxn.Sieve; // See http://pastebin.com/Evp36u52
  8.  
  9. /**
  10.  * Version 1.4
  11.  * Reads from and writes to files. Necessary when Scanner goes awry in file io is needed.
  12.  * <ul>
  13.  * <li>1.4 - Now supports writing to files as well! And encodings! Switching between reading and writing is also handled (but involves a lot of file operations and is not advised safe when debugging.)
  14.  * <li>1.3 - nemaed from FReader to NiceFile, and made its own library
  15.  * </ul>
  16.  * @author Katie
  17.  */
  18. public final class NiceFile {
  19.  
  20.     public static Sieve<String> commentedLineIgnorer(final String commentedLinesStartWith) {
  21.         return new Sieve<String>() {
  22.  
  23.             @Override
  24.             public Boolean eval(String in) {
  25.                 return in.startsWith(commentedLinesStartWith);
  26.             }
  27.         };
  28.     }
  29.     public static final char READ = 'r';
  30.     public static final char OVERWRITE = 'w';
  31.     public static final char APPEND = 'a';
  32.     private int rcounter;
  33.     private BufferedReader reader;
  34.     private FileWriter writer;
  35.     private String line;
  36.     private String fname;
  37.     private char method;
  38.     private Sieve<String> lineIgnorer = null;
  39.  
  40.     /**
  41.      * Read form a file (method=NiceFile.READ), ignoring all lines for which lineignore.eval(line contents) returns true.
  42.      * @param fname
  43.      * @param commentedLineMarker
  44.      */
  45.     public NiceFile(String fname, Sieve<String> lineIgnorer) {
  46.         this(fname, READ);
  47.         this.lineIgnorer = lineIgnorer;
  48.     }
  49.     /**
  50.      * Opens a stream to the specified file. Use isOK() to test success; no file not found exceptions will be thrown here.
  51.      * @param fname
  52.      */
  53.     public NiceFile(String fname, char method) {
  54.         this.fname = fname;
  55.         start(method);
  56.     }
  57.  
  58.     /**
  59.      * Get the file name
  60.      * @return
  61.      */
  62.     public String getName() {
  63.         return fname;
  64.     }
  65.  
  66.     private void start(char method) {
  67.         line = null;
  68.         reader = null;
  69.         line = null;
  70.         reader = null;
  71.         rcounter = 0;
  72.         this.method = method;
  73.         if (method == OVERWRITE || method == APPEND) {
  74.             this.method = method;
  75.             try {
  76.                 writer = new FileWriter(fname, method == APPEND);
  77.             } catch (IOException ex) {
  78.             }
  79.         } else {
  80.             this.method = READ;
  81.             try {
  82.                 reader = new BufferedReader(new FileReader(fname));
  83.             } catch (FileNotFoundException ex) {
  84.             }
  85.         }
  86.     }
  87.  
  88.     /**
  89.      * Tests whether the stream to the file has been opened successfully.
  90.      * @return true iff the stream is opened and ready to read from
  91.      */
  92.     public boolean isReaderOK() {
  93.         return reader != null;
  94.     }
  95.  
  96.     /**
  97.      * Tests whether the write stream to the file has been opened successfully.
  98.      * @return true iff the stream is opened and ready to write to
  99.      */
  100.     public boolean isWriterOK() {
  101.         return writer != null;
  102.     }
  103.  
  104.     /**
  105.      * Reads the next line in the file. Will return null if the stream is, or suddenly becomes, broken.
  106.      * @return the next line
  107.      */
  108.     public String nextLine() {
  109.         if (method != READ) {
  110.             int rc = rcounter;
  111.             this.stop();
  112.             this.start(APPEND);
  113.             rcounter = rc;
  114.             NiceFile temp = new NiceFile(fname,lineIgnorer);
  115.             temp.fastForward(rcounter);
  116.             rcounter++;
  117.             return temp.nextLine();
  118.         }
  119.         if (reader == null) {
  120.             return null;
  121.         }
  122.         try {
  123.             line = reader.readLine();
  124.             rcounter++;
  125.         } catch (IOException ex) {
  126.             line = null;
  127.             reader = null;
  128.         }
  129.         if (lineIgnorer != null && lineIgnorer.eval(line)) {
  130.             return nextLine();
  131.         } else {
  132.             return line;
  133.         }
  134.     }
  135.  
  136.     /**
  137.      * Returns the latest line fetched by nextLine();
  138.      * @return
  139.      */
  140.     public String currentLine() {
  141.         return line;
  142.     }
  143.  
  144.     /**
  145.      * Returns the number of lines read (useful for debugging).
  146.      * @return
  147.      */
  148.     public int linesRead() {
  149.         return rcounter;
  150.     }
  151.  
  152.     /**
  153.      * Severs the stream.
  154.      * @return
  155.      */
  156.     public boolean stop() {
  157.         if (reader == null && method == READ) {
  158.             return false;
  159.         }
  160.         if (writer == null) {
  161.             return false;
  162.         }
  163.         if (method == READ) {
  164.             try {
  165.                 reader.close();
  166.                 return true;
  167.             } catch (IOException ex) {
  168.                 return false;
  169.             }
  170.         }
  171.         try {
  172.             writer.close();
  173.             return true;
  174.         } catch (IOException ex) {
  175.             return false;
  176.         }
  177.     }
  178.  
  179.     public String get() {
  180.         StringBuilder sb = new StringBuilder();
  181.         while (nextLine() != null) {
  182.             sb.append(currentLine()).append("\n");
  183.         }
  184.         return sb.toString();
  185.     }
  186.  
  187.     public ArrayList<String> getList(boolean trimmed) {
  188.         ArrayList<String> out = new ArrayList<String>();
  189.         while (nextLine() != null) {
  190.             String l = currentLine();
  191.             if (trimmed) {
  192.                 l = l.trim();
  193.             }
  194.             if (trimmed && l.isEmpty()) {
  195.                 continue;
  196.             }
  197.             out.add(l);
  198.         }
  199.         return out;
  200.     }
  201.  
  202.     public boolean writeln(CharSequence cs) {
  203.         if (method != READ) {
  204.             if (writer == null) {
  205.                 return false;
  206.             }
  207.             try {
  208.                 writer.append(cs);
  209.                 writer.append("\n");
  210.                 return true;
  211.             } catch (IOException ex) {
  212.             }
  213.         } else {
  214.             int rc = rcounter;
  215.             this.stop();
  216.             NiceFile temp = new NiceFile(fname, APPEND);
  217.             boolean result = temp.writeln(cs);
  218.             temp.stop();
  219.             this.start(READ);
  220.             fastForward(rc);
  221.             return result;
  222.         }
  223.         return false;
  224.     }
  225.  
  226.     public boolean write(CharSequence cs) {
  227.         if (method != READ) {
  228.             if (writer == null) {
  229.                 return false;
  230.             }
  231.             try {
  232.                 writer.append(cs);
  233.                 return true;
  234.             } catch (IOException ex) {
  235.                 ex.printStackTrace();
  236.             }
  237.         } else {
  238.             int rc = rcounter;
  239.             this.stop();
  240.             NiceFile temp = new NiceFile(fname, APPEND);
  241.             boolean result = temp.write(cs);
  242.             temp.stop();
  243.             this.start(READ);
  244.             fastForward(rc);
  245.             return result;
  246.         }
  247.         return false;
  248.     }
  249.  
  250.     public boolean fastForward(int goal) {
  251.         while (goal > rcounter) {
  252.             if (nextLine() == null) {
  253.                 return false;
  254.             }
  255.         }
  256.         return true;
  257.     }
  258.  
  259.     public static void main(String args[]) {
  260.         NiceFile nf = new NiceFile("test.txt", NiceFile.OVERWRITE);
  261.         System.out.println(nf.writeln("test 1"));
  262.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  263.         System.out.println(nf.writeln("test 2"));
  264.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  265.         System.out.println(nf.writeln("test 3"));
  266.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  267.         nf.stop();
  268.         nf = new NiceFile("test.txt", NiceFile.APPEND);
  269.         System.out.println(nf.writeln("test 1"));
  270.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  271.         System.out.println(nf.writeln("test 2"));
  272.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  273.         System.out.println(nf.writeln("test 3"));
  274.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  275.         nf.stop();
  276.         nf = new NiceFile("test.txt", NiceFile.READ);
  277.         System.out.println(nf.writeln("test 1"));
  278.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  279.         System.out.println(nf.writeln("test 2"));
  280.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  281.         System.out.println(nf.writeln("test 3"));
  282.         System.out.println(nf.nextLine() + " @" + nf.rcounter);
  283.         nf.stop();
  284.     }
  285.  
  286.     public static boolean append(String filename, CharSequence in) {
  287.         NiceFile nf = new NiceFile(filename, APPEND);
  288.         boolean out = nf.write(in);
  289.         nf.stop();
  290.         return out;
  291.     }
  292.  
  293.     public static boolean write(String filename, CharSequence in) {
  294.         NiceFile nf = new NiceFile(filename, OVERWRITE);
  295.         boolean out = nf.write(in);
  296.         nf.stop();
  297.         return out;
  298.     }
  299.  
  300.     public static String read(String filename, String... commentDelim) {
  301.         NiceFile nf = new NiceFile(filename,commentDelim.length==0?null:commentedLineIgnorer(commentDelim[0]));
  302.         return nf.get();
  303.     }
  304.  
  305.     public static ArrayList<String> read(String filename, boolean trimmed, String... commentDelim) {
  306.         NiceFile nf = new NiceFile(filename,commentDelim.length==0?null:commentedLineIgnorer(commentDelim[0]));
  307.         return nf.getList(trimmed);
  308.     }
  309. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement