Java/File Input Output/Text Read Write

Материал из Java эксперт
Перейти к: навигация, поиск

An iterator that breaks text into lines. The result is equal to BufferedReader.readLine().

   <source lang="java">
   

/*

* JCommon : a free general purpose class library for the Java(tm) platform
* 
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
* 
* Project Info:  http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it 
* under the terms of the GNU Lesser General Public License as published by 
* the Free Software Foundation; either version 2.1 of the License, or 
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but 
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
* USA.  
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
* in the United States and other countries.]
*
* ----------------------
* LineBreakIterator.java
* ----------------------
* (C)opyright 2003, by Thomas Morgner and Contributors.
*
* Original Author:  Thomas Morgner;
* Contributor(s):   David Gilbert (for Object Refinery Limited);
*
* $Id: LineBreakIterator.java,v 1.4 2005/11/03 09:55:26 mungady Exp $
*
* Changes
* -------
* 13-03-2003 : Initial version
*/

import java.util.Iterator; /**

* An iterator that breaks text into lines. The result is equal to
* BufferedReader.readLine().
* 
* @author Thomas Morgner
*/

public class LineBreakIterator implements Iterator {

 /** A useful constant. */
 public static final int DONE = -1;
 /** Storage for the text. */
 private char[] text;
 /** The current position. */
 private int position;
 /**
  * Default constructor.
  */
 public LineBreakIterator() {
   setText("");
 }
 /**
  * Creates a new line break iterator.
  * 
  * @param text
  *          the text to be broken up.
  */
 public LineBreakIterator(final String text) {
   setText(text);
 }
 /**
  * Returns the position of the next break.
  * 
  * @return A position.
  */
 public synchronized int nextPosition() {
   if (this.text == null) {
     return DONE;
   }
   if (this.position == DONE) {
     return DONE;
   }
   // recognize \n, \r, \r\n
   final int nChars = this.text.length;
   int nextChar = this.position;
   for (;;) {
     if (nextChar >= nChars) {
       /* End of text reached */
       this.position = DONE;
       return DONE;
     }
     boolean eol = false;
     char c = 0;
     int i;
     // search the next line break, either \n or \r
     for (i = nextChar; i < nChars; i++) {
       c = this.text[i];
       if ((c == "\n") || (c == "\r")) {
         eol = true;
         break;
       }
     }
     nextChar = i;
     if (eol) {
       nextChar++;
       if (c == "\r") {
         if ((nextChar < nChars) && (this.text[nextChar] == "\n")) {
           nextChar++;
         }
       }
       this.position = nextChar;
       return (this.position);
     }
   }
 }
 /**
  * Same like next(), but returns the End-Of-Text as if there was a linebreak
  * added (Reader.readLine() compatible)
  * 
  * @return The next position.
  */
 public int nextWithEnd() {
   final int pos = this.position;
   if (pos == DONE) {
     return DONE;
   }
   if (pos == this.text.length) {
     this.position = DONE;
     return DONE;
   }
   final int retval = nextPosition();
   if (retval == DONE) {
     return this.text.length;
   }
   return retval;
 }
 /**
  * Returns the text to be broken up.
  * 
  * @return The text.
  */
 public String getText() {
   return new String(this.text);
 }
 /**
  * Sets the text to be broken up.
  * 
  * @param text
  *          the text.
  */
 public void setText(final String text) {
   this.position = 0;
   this.text = text.toCharArray();
 }
 /**
  * Returns true if the iteration has more elements. (In other
  * words, returns true if next would return an element
  * rather than throwing an exception.)
  * 
  * @return true if the iterator has more elements.
  */
 public boolean hasNext() {
   return (this.position != DONE);
 }
 /**
  * Returns the next element in the iteration.
  * 
  * @return the next element in the iteration.
  */
 public Object next() {
   if (this.position == DONE) {
     // allready at the end ...
     return null;
   }
   final int lastFound = this.position;
   int pos = nextWithEnd();
   if (pos == DONE) {
     // the end of the text has been reached ...
     return new String(this.text, lastFound, this.text.length - lastFound);
   }
   // step one char back
   if (pos > 0) {
     final int end = lastFound;
     for (; ((pos) > end) && ((this.text[pos - 1] == "\n") || this.text[pos - 1] == "\r"); pos--) {
       // search the end of the current linebreak sequence ..
     }
   }
   // System.out.println ("text: " + new String (text));
   // System.out.println ("pos: " + pos + " lastFound: " + lastFound);
   return new String(this.text, lastFound, pos - lastFound);
 }
 /**
  * 
  * Removes from the underlying collection the last element returned by the
  * iterator (optional operation). This method can be called only once per call
  * to next. The behavior of an iterator is unspecified if the
  * underlying collection is modified while the iteration is in progress in any
  * way other than by calling this method.
  * 
  * @exception UnsupportedOperationException
  *              if the remove operation is not supported by this
  *              Iterator.
  * @exception IllegalStateException
  *              if the next method has not yet been called, or the
  *              remove method has already been called after the
  *              last call to the next method.
  */
 public void remove() {
   throw new UnsupportedOperationException("This iterator is read-only.");
 }

}



 </source>
   
  
 
  



Compare text file line by line

   <source lang="java">

/*

  • Copyright 2004 The Apache Software Foundation
  • Licensed under the Apache License, Version 2.0 (the "License");
  • you may not use this file except in compliance with the License.
  • You may obtain a copy of the License at
  • http://www.apache.org/licenses/LICENSE-2.0
  • Unless required by applicable law or agreed to in writing, software
  • distributed under the License is distributed on an "AS IS" BASIS,
  • WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  • See the License for the specific language governing permissions and
  • limitations under the License.
  • /

//based on Apache technology http://www.apache.org import java.io.IOException; import java.io.LineNumberReader; import java.io.Reader; import java.util.List;

public class Diff {

   public static void readersAsText(Reader r1, String name1, Reader r2, String name2,
       List diffs)
       throws IOException
   {
       LineNumberReader reader1 = new LineNumberReader(r1);
       LineNumberReader reader2 = new LineNumberReader(r2);
       String line1 = reader1.readLine();
       String line2 = reader2.readLine();
       while (line1 != null && line2 != null)
       {
           if (!line1.equals(line2))
           {
               diffs.add("File \"" + name1 + "\" and file \"" +
                   name2 + "\" differ at line " + reader1.getLineNumber() +
                   ":" + "\n" + line1 + "\n" + line2);
               break;
           }
           line1 = reader1.readLine();
           line2 = reader2.readLine();
       }
       if (line1 == null && line2 != null)
           diffs.add("File \"" + name2 + "\" has extra lines at line " +
               reader2.getLineNumber() + ":\n" + line2);
       if (line1 != null && line2 == null)
           diffs.add("File \"" + name1 + "\" has extra lines at line " +
               reader1.getLineNumber() + ":\n" + line1);
   }

}

 </source>
   
  
 
  



CRLF Print Writer

   <source lang="java">
    

/* -----------------------------------------------------------

* nntp//rss - a bridge between the RSS world and NNTP clients
* Copyright (c) 2002, 2003 Jason Brome.  All Rights Reserved.
*
* email: nntprss@methodize.org
* mail:  Methodize Solutions
*        PO Box 3865
*        Grand Central Station
*        New York NY 10163
* 
* This file is part of nntp//rss
* 
* nntp//rss is free software; you can redistribute it 
* and/or modify it under the terms of the GNU General 
* Public License as published by the Free Software Foundation; 
* either version 2 of the License, or (at your option) any 
* later version.
*
* This program is distributed in the hope that it will be 
* useful, but WITHOUT ANY WARRANTY; without even the implied 
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
* PURPOSE.  See the GNU General Public License for more 
* details.
*
* You should have received a copy of the GNU General Public 
* License along with this program; if not, write to the 
* Free Software Foundation, Inc., 59 Temple Place, Suite 330, 
* Boston, MA  02111-1307  USA
* ----------------------------------------------------- */

import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; /**

* 
* Wrapper class - used for output writer in NNTP communications
* All lines must end in CR/LF - if println is used in
* standard PrintWriter implementation, platform specific
* line termination will be used - e.g. \r\n *or* \n
* 
* @author Jason Brome <jason@methodize.org>
* @version $Id: CRLFPrintWriter.java,v 1.3 2003/01/22 05:11:23 jasonbrome Exp $
*/

public class CRLFPrintWriter extends PrintWriter {

 private static final String CRLF = "\r\n";
 
 public CRLFPrintWriter(OutputStream out) {
   super(out);
 }
 
 public CRLFPrintWriter(OutputStream out, boolean autoFlush) {
   super(out, autoFlush);
 }
 public CRLFPrintWriter(Writer out) {
   super(out);
 }
 
 public CRLFPrintWriter(Writer out, boolean autoFlush) {
   super(out, autoFlush);
 }
 
 
 /**
  * @see java.io.PrintWriter#println()
  */
 public void println() {
   super.print(CRLF);
 }
 /**
  * @see java.io.PrintWriter#println(boolean)
  */
 public void println(boolean arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(char)
  */
 public void println(char arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(char[])
  */
 public void println(char[] arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(double)
  */
 public void println(double arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(float)
  */
 public void println(float arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(int)
  */
 public void println(int arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(long)
  */
 public void println(long arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(Object)
  */
 public void println(Object arg0) {
   super.print(arg0);
   println();
 }
 /**
  * @see java.io.PrintWriter#println(String)
  */
 public void println(String arg0) {
   super.print(arg0);
   println();
 }

}



 </source>
   
  
 
  



CRLF Terminated Reader

   <source lang="java">
    

/****************************************************************

* Licensed to the Apache Software Foundation (ASF) under one   *
* or more contributor license agreements.  See the NOTICE file *
* distributed with this work for additional information        *
* regarding copyright ownership.  The ASF licenses this file   *
* to you under the Apache License, Version 2.0 (the            *
* "License"); you may not use this file except in compliance   *
* with the License.  You may obtain a copy of the License at   *
*                                                              *
*   http://www.apache.org/licenses/LICENSE-2.0                 *
*                                                              *
* Unless required by applicable law or agreed to in writing,   *
* software distributed under the License is distributed on an  *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
* KIND, either express or implied.  See the License for the    *
* specific language governing permissions and limitations      *
* under the License.                                           *
****************************************************************/

import java.io.InputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.IOException; /**

* A Reader for use with SMTP or other protocols in which lines
* must end with CRLF.  Extends Reader and overrides its 
* readLine() method.  The Reader readLine() method cannot
* serve for SMTP because it ends lines with either CR or LF alone. 
*/

public class CRLFTerminatedReader extends Reader {

   public class TerminationException extends IOException {
       private int where;
       public TerminationException(int where) {
           super();
           this.where = where;
       }
       public TerminationException(String s, int where) {
           super(s);
           this.where = where;
       }
       public int position() {
           return where;
       }
   }
   public class LineLengthExceededException extends IOException {
       public LineLengthExceededException(String s) {
           super(s);
       }
   }
   /**
    * Constructs this CRLFTerminatedReader.
    * @param in an InputStream
    * @param charsetName the String name of a supported charset.  
    * "ASCII" is common here.
    * @throws UnsupportedEncodingException if the named charset
    * is not supported
    */
   InputStream in;
   public CRLFTerminatedReader(InputStream in) {
   this.in = in;
   }
   public CRLFTerminatedReader(InputStream in, String enc) throws UnsupportedEncodingException {
       this(in);
   }
   private StringBuffer lineBuffer = new StringBuffer();
   private final int
           EOF = -1,
           CR  = 13,
           LF  = 10;
   private int tainted = -1;
   /**
    * Read a line of text which is terminated by CRLF.  The concluding
    * CRLF characters are not returned with the String, but if either CR
    * or LF appears in the text in any other sequence it is returned
    * in the String like any other character.  Some characters at the 
    * end of the stream may be lost if they are in a "line" not
    * terminated by CRLF.
    * 
    * @return either a String containing the contents of a 
    * line which must end with CRLF, or null if the end of the 
    * stream has been reached, possibly discarding some characters 
    * in a line not terminated with CRLF. 
    * @throws IOException if an I/O error occurs.
    */
   public String readLine() throws IOException{
       //start with the StringBuffer empty
       lineBuffer.delete(0, lineBuffer.length());
       /* This boolean tells which state we are in,
        * depending upon whether or not we got a CR
        * in the preceding read().
        */ 
       boolean cr_just_received = false;
       // Until we add support for specifying a maximum line lenth as
       // a Service Extension, limit lines to 2K, which is twice what
       // RFC 2821 4.5.3.1 requires.
       while (lineBuffer.length() <= 2048) {
           int inChar = read();
           if (!cr_just_received){
               //the most common case, somewhere before the end of a line
               switch (inChar){
                   case CR  :  cr_just_received = true;
                               break;
                   case EOF :  return null;   // premature EOF -- discards data(?)
                   case LF  :  //the normal ending of a line
                       if (tainted == -1) tainted = lineBuffer.length();
                       // intentional fall-through
                   default  :  lineBuffer.append((char)inChar);
               }
           }else{
               // CR has been received, we may be at end of line
               switch (inChar){
                   case LF  :  // LF without a preceding CR
                       if (tainted != -1) {
                           int pos = tainted;
                           tainted = -1;
                           throw new TerminationException("\"bare\" CR or LF in data stream", pos);
                       }
                       return lineBuffer.toString();
                   case EOF :  return null;   // premature EOF -- discards data(?)
                   case CR  :  //we got two (or more) CRs in a row
                       if (tainted == -1) tainted = lineBuffer.length();
                       lineBuffer.append((char)CR);
                       break;
                   default  :  //we got some other character following a CR
                       if (tainted == -1) tainted = lineBuffer.length();
                       lineBuffer.append((char)CR);
                       lineBuffer.append((char)inChar);
                       cr_just_received = false;
               }
           }
       }//while
       throw new LineLengthExceededException("Exceeded maximum line length");
   }//method readLine()
   public int read() throws IOException {
   return in.read();
   }
   public boolean ready() throws IOException {
   return in.available() > 0;
   }
   public int read(char cbuf[], int  off, int  len) throws IOException {
   byte [] temp = new byte[len];
   int result = in.read(temp, 0, len);
   for (int i=0;i<result;i++) cbuf[i] = (char) temp[i];
   return result;
   }
   public void close() throws IOException {
   in.close();
   }

}



 </source>
   
  
 
  



Data Text Writer

   <source lang="java">
  

//** Copyright Statement *************************************************** //The Salmon Open Framework for Internet Applications (SOFIA) // Copyright (C) 1999 - 2002, Salmon LLC // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License version 2 // as published by the Free Software Foundation; // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information please visit http://www.salmonllc.ru //** End Copyright Statement ***************************************************

///////////////////////// //$Archive: /JADE/SourceCode/com/salmonllc/util/DataTextWriter.java $ //$Author: Dan $ //$Revision: 7 $ //$Modtime: 10/30/02 2:59p $ /////////////////////////

import java.util.*; import java.io.*; /**

* This object allows you to write a flat text file with data elements separated by Separators and such. 
*/

public class DataTextWriter {

 private int NumColumns=0;
 private Vector[] Columns;
 private String LineBreak="\r\n";
 private String Separator=",";
 private boolean Quoted=false;
 private char QuoteCharacter="\0";
 private StringBuffer sbTextBuffer=new StringBuffer();

/**

* Builds a DataTextWriter with each row containing iNumColumns.
* @param iNumCols The number of columns in a row of the DataTextWriter.
*/ 

public DataTextWriter(int iNumCols) {

 this(iNumCols,"","","\0",false);

} /**

* Builds a DataTextWriter with each row containing iNumCols and each piece of Data separated by sSeparator.
* @param iNumCols The number of columns in a row of the DataTextWriter.
* @param sSeparator The separator used to separate data columns in a row.
*/ 

public DataTextWriter(int iNumCols,String sSeparator) {

 this(iNumCols,sSeparator,"","\0",false);

} /**

* Builds a DataTextWriter with each row containing iNumCols and each piece of Data separated by sSeparator 
* and row separated by sLineBreak.
* @param iNumCols The number of columns in a row of the DataTextWriter.
* @param sSeparator The separator used to separate data columns in a row.
* @param sLineBreak The separator used to separate individual rows.
*/ 

public DataTextWriter(int iNumCols,String sSeparator,String sLineBreak) {

 this(iNumCols,sSeparator,sLineBreak,"\0",false);

} /**

* Builds a DataTextWriter with each row containing iNumColumns and each piece of Data separated by sSeparator 
* and row separated by sLineBreak and each piece of Data is surrounded by cQuoteChar if bQuoted is true.
* @param iNumCols The number of columns in a row of the DataTextWriter.
* @param sSeparator The separator used to separate data columns in a row.
* @param sLineBreak The separator used to separate individual rows.
* @param cQuoteChar The character used to quote indivividual data columns.
* @param bQuoted The flag to indicate if data columns are to be quoted.
*/ 

public DataTextWriter(int iNumCols,String sSeparator,String sLineFeed,char cQuoteChar,boolean bQuoted) {

 NumColumns=iNumCols;
 Separator=sSeparator;
 LineBreak=sLineFeed;
 QuoteCharacter=cQuoteChar;
 Quoted=bQuoted;
 Columns=new Vector[iNumCols];
 for (int i=0;i<iNumCols;i++)
   Columns[i]=new Vector(100,100);

} /**

* Adds a piece of data to a specific column in this DataTextWriter. 
* @param iColumn The column which the specified data belongs to.
* @param sData The data for the specified column.
*/ 

public void addData(int iColumn,String sData) throws Exception {

 if (iColumn<0 || iColumn>=NumColumns)
   throw new Exception("Column Index is out of range. Valid Range is (0-"+(NumColumns-1)+").");
 Columns[iColumn].addElement(sData);
 int iCount=Columns[0].size(); 
 for (int i=1;i<NumColumns;i++)
    if (Columns[i].size()!=iCount)
      return;
 int i=Columns[iColumn].size()-1;
 for (int j=0;j<(NumColumns-1);j++) {
   if (Quoted) 
     sbTextBuffer.append(QuoteCharacter+(String)Columns[j].elementAt(i)+QuoteCharacter+Separator);
   else
   sbTextBuffer.append((String)Columns[j].elementAt(i)+Separator);
  }
 if (Quoted) 
   sbTextBuffer.append(QuoteCharacter+(String)Columns[NumColumns-1].elementAt(i)+QuoteCharacter+LineBreak);
 else
   sbTextBuffer.append((String)Columns[NumColumns-1].elementAt(i)+LineBreak);

} /**

* This method returns the Data in DataTextWriter in formatted output string.
* @return Formatted Output
*/

public String getText() /*throws DataTextWriterException*/ { // StringBuffer sb=new StringBuffer(); /* int iCount=Columns[0].size();

 for (int i=1;i<NumColumns;i++)
    if (Columns[i].size()!=iCount)
      throw new DataTextWriterException("There is not an equal number data values in each column.");*/

/* for (int i=0;i<iCount;i++) {

   for (int j=0;j<NumColumns-1;j++) {
   if (Quoted) 
       sb.append(QuoteCharacter+(String)Columns[j].elementAt(i)+QuoteCharacter+Separator);
   else
     sb.append((String)Columns[j].elementAt(i)+Separator);
    }
   if (Quoted) 
   sb.append(QuoteCharacter+(String)Columns[NumColumns-1].elementAt(i)+QuoteCharacter+LineBreak);
   else
   sb.append((String)Columns[NumColumns-1].elementAt(i)+LineBreak);
  } */
 return sbTextBuffer.toString();

} /**

* This method returns the length of the Data in DataTextWriter in formatted output string.
* @return Formatted Output
*/

public int getTextLength() {

 return sbTextBuffer.length();

} /**

* Sets the LineBreak Separator in this DataTextWriter. 
* @param sLineBreak The separator used to separate individual rows.
*/ 

public void setLineBreak(String sLineBreak) {

 LineBreak=sLineBreak;

} /**

* Sets the Character to be used for Quoting Data Columns in this DataTextWriter. 
* @param cQuoteChar The character used to quote individual data columns.
*/ 

public void setQuoteCharacter(char cQuoteChar) {

 QuoteCharacter=cQuoteChar;

} /**

* Sets the Flag to to inicate that Data Columns are to be quoted in this DataTextWriter. 
* @param bQuoted The flag used to indicate if data columns are quoted.
*/ 

public void setQuoted(boolean bQuoted) {

 Quoted=bQuoted;

} /**

* Sets the Separator to be used for separating individual Data Columns in this DataTextWriter. 
* @param sSeparator The separator used to separate individual data columns.
*/ 

public void setSeparator(String sSeparator) {

 Separator=sSeparator;

} /**

* This method creates a flat file containing the data added to this DataTextWriter.
* @param sFilename The name of flat file to create.
*/

public void writeFile(String sFilename) throws Exception {

 try {
   FileOutputStream fos=new FileOutputStream(sFilename);
   PrintWriter pw=new PrintWriter(fos);
   pw.print(getText());
   pw.close();
   fos.close();
  }
 catch(Exception e) {
   throw new Exception(e.getMessage());
  }            

} }


 </source>
   
  
 
  



Dump a String to a text file with encoding.

   <source lang="java">
  

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer;

public class Main {

 /**
  * Dump a String to a text file.
  *
  * @param file The output file
  * @param string The string to be dumped
  * @param encoding The encoding for the output file or null for default platform encoding
  * @exception IOException IO Error
  */
 public static void serializeString(File file, String string, String encoding)
 throws IOException {
     final Writer fw =
             (encoding == null)?
             new FileWriter(file):
             new OutputStreamWriter(new FileOutputStream(file), encoding);
     try {
         fw.write(string);
         fw.flush();
     } finally {
         fw.close();
     }
 }

}


 </source>
   
  
 
  



Find a pattern within a file

   <source lang="java">
    

/*

* @(#)Grep.java  1.3 01/12/13
* Search a list of files for lines that match a given regular-expression
* pattern.  Demonstrates NIO mapped byte buffers, charsets, and regular
* expressions.
*
* Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or 
* without modification, are permitted provided that the following 
* conditions are met:
* 
* -Redistributions of source code must retain the above copyright  
* notice, this  list of conditions and the following disclaimer.
* 
* -Redistribution in binary form must reproduct the above copyright 
* notice, this list of conditions and the following disclaimer in 
* the documentation and/or other materials provided with the 
* distribution.
* 
* Neither the name of Sun Microsystems, Inc. or the names of 
* contributors may be used to endorse or promote products derived 
* from this software without specific prior written permission.
* 
* This software is provided "AS IS," without a warranty of any 
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND 
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, 
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY 
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY 
* DAMAGES OR LIABILITIES  SUFFERED BY LICENSEE AS A RESULT OF  OR 
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR 
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE 
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, 
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER 
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF 
* THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN 
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* 
* You acknowledge that Software is not designed, licensed or 
* intended for use in the design, construction, operation or 
* maintenance of any nuclear facility. 
*/

import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /**

* This is a utility class to find a pattern within a file, specifically the
* sense.idx file.
* 
* @author brett
* 
*/

public class Grep {

 /**
  * Set the character set for the file.
  */
 private static Charset charset = Charset.forName("ISO-8859-15");
 /**
  * The decoder for the file.
  */
 private static CharsetDecoder decoder = charset.newDecoder();
 /**
  * Line parsing pattern.
  */
 private static Pattern linePattern = Pattern.rupile(".*\r?\n");
 /**
  * Input pattern we"re looking for.
  */
 private static Pattern pattern;
 /**
  * The character buffer reference.
  */
 private static CharBuffer indexFile;
 /**
  * Compiles the pattern.
  * 
  * @param pat
  *          regex
  */
 private static void compile(String pat) {
   try {
     pattern = Pattern.rupile(pat);
   } catch (PatternSyntaxException x) {
     System.err.println(x.getMessage());
   }
 }
 /**
  * Use the linePattern to break the given CharBuffer into lines, applying the
  * input pattern to each line to see if we have a match
  */
 private static List grep() {
   List matches = new ArrayList();
   Matcher lm = linePattern.matcher(indexFile); // Line matcher
   Matcher pm = null; // Pattern matcher
   int lines = 0;
   while (lm.find()) {
     lines++;
     CharSequence cs = lm.group(); // The current line
     if (pm == null)
       pm = pattern.matcher(cs);
     else
       pm.reset(cs);
     if (pm.find()) {
       matches.add(cs.toString());
     }
     if (lm.end() == indexFile.limit())
       break;
   }
   return matches;
 }
 public static void setFile(File f) throws IOException {
   FileInputStream fis = new FileInputStream(f);
   FileChannel fc = fis.getChannel();
   // Get the file"s size and then map it into memory
   int sz = (int) fc.size();
   MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
   // Decode the file into a char buffer
   indexFile = decoder.decode(bb);
   fc.close();
 }
 /**
  * Search for occurrences in the given file of the offset, then find the
  * appropriate lemma.
  * 
  * @param f
  * @param synsetOffset
  * @return
  * @throws IOException
  */
 public static List grep(String synsetOffset) throws IOException {
   compile(synsetOffset);
   // Perform the search
   List matches = grep();
   return matches;
 }
 /**
  * Search for occurrences in the given file of the offset, then find the
  * appropriate lemma.
  * 
  * @param f
  * @param synsetOffset
  * @return
  * @throws IOException
  */
 public static String grep(String synsetOffset, String lemma) throws IOException {
   compile(synsetOffset);
   String m = "";
   // Perform the search
   List matches = grep();
   for (int i = 0; i < matches.size(); i++) {
     String match = (String) matches.get(i);
     if (match.indexOf(lemma) != -1) {
       m = match;
     }
   }
   return m;
 }

}



 </source>
   
  
 
  



Gets the content from a File as String Array List

   <source lang="java">
    

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; /*

* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2005 Marc Eppelmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Provides general global file utility methods
*
* @author marc.eppelmann
*/

class FileUtil {

   //~ Constructors ***********************************************************************
   /**
    * Creates a new FileUtil object.
    */
   public FileUtil()
   {
   }
   //~ Methods ****************************************************************************
   /**
    * Gets the content from a File as StringArray List.
    *
    * @param fileName A file to read from.
    * @return List of individual line of the specified file. List may be empty but not
    *         null.
    * @throws IOException
    */
   public static ArrayList getFileContent(String fileName)
           throws IOException
   {
       ArrayList result = new ArrayList();
       File aFile = new File(fileName);
       if (!aFile.isFile())
       {
           //throw new IOException( fileName + " is not a regular File" );
           return result; // None
       }
       BufferedReader reader = null;
       try
       {
           reader = new BufferedReader(new FileReader(aFile));
       }
       catch (FileNotFoundException e1)
       {
           // TODO handle Exception
           e1.printStackTrace();
           return result;
       }
       String aLine = null;
       while ((aLine = reader.readLine()) != null)
       {
           result.add(aLine + "\n");
       }
       reader.close();
       return result;
   }
   /**
    * Searches case sensitively, and returns true if the given SearchString occurs in the
    * first File with the given Filename.
    *
    * @param aFileName     A files name
    * @param aSearchString the string search for
    * @return true if found in the file otherwise false
    */
   public static boolean fileContains(String aFileName, String aSearchString)
   {
       return (fileContains(aFileName, aSearchString, false));
   }
   /**
    * Tests if the given File contains the given Search String
    *
    * @param aFileName             A files name
    * @param aSearchString         the String to search for
    * @param caseInSensitiveSearch If false the Search is casesensitive
    * @return true if found in the file otherwise false
    */
   public static boolean fileContains(String aFileName, String aSearchString,
                                      boolean caseInSensitiveSearch)
   {
       boolean result = false;
       String searchString = caseInSensitiveSearch
               ? aSearchString.toLowerCase() : aSearchString;
       ArrayList fileContent = new ArrayList();
       try
       {
           fileContent = getFileContent(aFileName);
       }
       catch (IOException e)
       {
           // TODO handle Exception
           e.printStackTrace();
       }
       Iterator linesIter = fileContent.iterator();
       while (linesIter.hasNext())
       {
           String currentline = (String) linesIter.next();
           if (caseInSensitiveSearch)
           {
               currentline = currentline.toLowerCase();
           }
           if (currentline.indexOf(searchString) > -1)
           {
               result = true;
               break;
           }
       }
       return result;
   }
   /**
    * Gets file date and time.
    *
    * @param url The URL of the file for which date and time will be returned.
    * @return Returns long value which is the date and time of the file. If any error
    *         occures returns -1 (=no file date and time available).
    */
   public static long getFileDateTime(URL url)
   {
       if (url == null)
       {
           return -1;
       }
       String fileName = url.getFile();
       if (fileName.charAt(0) == "/" || fileName.charAt(0) == "\\")
       {
           fileName = fileName.substring(1, fileName.length());
       }
       try
       {
           File file = new File(fileName);
           // File name must be a file or a directory.
           if (!file.isDirectory() && !file.isFile())
           {
               return -1;
           }
           return file.lastModified();
       }
       catch (java.lang.Exception e)
       {   // Trap all Exception based exceptions and return -1.
           return -1;
       }
   }
   public static String[] getFileNames(String dirPath) throws Exception
   {
       return getFileNames(dirPath, null);
   }
   public static String[] getFileNames(String dirPath, FilenameFilter fileNameFilter) throws Exception
   {
       String fileNames[] = null;
       File dir = new File(dirPath);
       if (dir.isDirectory())
       {
           if (fileNameFilter != null)
           {
               fileNames = dir.list(fileNameFilter);
           }
           else
           {
               fileNames = dir.list();
           }
       }
       return fileNames;
   }
   /**
    * Test main
    *
    * @param args
    */
   public static void main(String[] args)
   {
   }

}



 </source>
   
  
 
  



Java File Generator

   <source lang="java">
    

/* Copyright (c) 2008, Paul Cager.

* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
*     * Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /**

* Generates boiler-plate files from templates. Only very basic
* template processing is supplied - if we need something more
* sophisticated I suggest we use a third-party library.
* 
* @author paulcager
* @since 4.2
*/

public class JavaFileGenerator {

 /**
  * @param templateName the name of the template. E.g. 
  *        "/templates/Token.template".
  * @param options the processing options in force, such
  *        as "STATIC=yes" 
  */
 public JavaFileGenerator(String templateName, Map options) {
   this.templateName = templateName;
   this.options = options;
 }
 private final String templateName;
 private final Map options; 
 
 private String currentLine;
 /**
  * Generate the output file.
  * @param out
  * @throws IOException
  */
 public void generate(PrintWriter out) throws IOException
 {
   InputStream is = getClass().getResourceAsStream(templateName);
   if (is == null)
     throw new IOException("Invalid template name: " + templateName);
   BufferedReader in = new BufferedReader(new InputStreamReader(is)); 
   process(in, out, false);
 }
 
 private String peekLine(BufferedReader in) throws IOException
 {
   if (currentLine == null)
     currentLine = in.readLine();
   
   return currentLine;
 }
 
 private String getLine(BufferedReader in) throws IOException
 {
   String line = currentLine;
   currentLine = null;
   
   if (line == null)
     in.readLine();
   
   return line;
 }
 
 private boolean evaluate(String condition)
 {
   condition = condition.trim();
   
   Object obj = options.get(condition);
   
   if (obj == null)
   {
     return condition.equalsIgnoreCase("true") || condition.equalsIgnoreCase("yes");
   }
   
   if (obj instanceof Boolean)
   {
     return ((Boolean)obj).booleanValue();
   }
   else if (obj instanceof String)
   {
     String string = ((String)obj).trim();
     return string.length() > 0 && !string.equalsIgnoreCase("false") && !string.equalsIgnoreCase("no");
   }
   
   return false;
 }
 
 private String substitute(String text) throws IOException
 {
   int startPos;
   
   if ( (startPos = text.indexOf("${")) == -1)
   {
     return text;
   }
   
   // Find matching "}".
   int braceDepth = 1;
   int endPos = startPos + 2;
   
   while ( endPos < text.length() && braceDepth > 0)
   {
     if (text.charAt(endPos) == "{")
       braceDepth++;
     else if (text.charAt(endPos) == "}")
       braceDepth--;
     
     endPos++;
   }
   
   if (braceDepth != 0)
     throw new IOException("Mismatched \"{}\" in template string: " + text); 
   
   final String variableExpression = text.substring(startPos + 2, endPos - 1);
   // Find the end of the variable name
   String value = null;
   
   for (int i = 0; i < variableExpression.length(); i++)
   {
     char ch = variableExpression.charAt(i);
     
     if (ch == ":" && i < variableExpression.length() - 1 && variableExpression.charAt(i+1) == "-" )
     {
       value = substituteWithDefault(variableExpression.substring(0, i), variableExpression.substring(i + 2));
       break;
     }
     else if (ch == "?")
     {
       value = substituteWithConditional(variableExpression.substring(0, i), variableExpression.substring(i + 1));
       break;
     }
     else if (ch != "_" && !Character.isJavaIdentifierPart(ch))
     {
       throw new IOException("Invalid variable in " + text);
     }
   }
   
   if (value == null)
   {
     value = substituteWithDefault(variableExpression, "");
   }
   
   return text.substring(0, startPos) + value + text.substring(endPos);
 }
 
 /**
  * @param substring
  * @param defaultValue
  * @return
  * @throws IOException 
  */
 private String substituteWithConditional(String variableName, String values) throws IOException
 {
   // Split values into true and false values.
   
   int pos = values.indexOf(":");
   if (pos == -1)
     throw new IOException("No ":" separator in " + values);
   
   if (evaluate(variableName))
     return substitute(values.substring(0, pos));
   else
     return substitute(values.substring(pos + 1));
 }
 /**
  * @param variableName
  * @param defaultValue
  * @return
  */
 private String substituteWithDefault(String variableName, String defaultValue) throws IOException
 {
   Object obj = options.get(variableName.trim());
   if (obj == null || obj.toString().length() == 0)
     return substitute(defaultValue);
   
   return obj.toString();
 }
 private void write(PrintWriter out, String text) throws IOException
 {
   while ( text.indexOf("${") != -1)
   {
     text = substitute(text);
   }
   
   out.println(text);
 }
 
 private void process(BufferedReader in, PrintWriter out, boolean ignoring)  throws IOException
 {

// out.println("*** process ignore=" + ignoring + " : " + peekLine(in));

   while ( peekLine(in) != null)
   {
     if (peekLine(in).trim().startsWith("#if"))
     {
       String line = getLine(in).trim();
       final boolean condition = evaluate(line.substring(3).trim());
       
       process(in, out, ignoring || !condition);
       
       if (peekLine(in) != null && peekLine(in).trim().startsWith("#else"))
       {
         getLine(in);   // Discard the #else line
         process(in, out, ignoring || condition);
       }
       
       line = getLine(in);
       
       if (line == null)
         throw new IOException("Missing \"#fi\"");
       
       if (!line.trim().startsWith("#fi"))
         throw new IOException("Expected \"#fi\", got: " + line);
     }
     else if (peekLine(in).trim().startsWith("#")) 
     {
       break;
     }
     else
     {
       String line = getLine(in);
       if (!ignoring) write(out, line);
     }
   }
   
   out.flush();
 }
 
 public static void main(String[] args) throws Exception
 {
   Map map = new HashMap();
   map.put("falseArg", Boolean.FALSE);
   map.put("trueArg", Boolean.TRUE);
   map.put("stringValue", "someString");
   
   new JavaFileGenerator(args[0], map).generate(new PrintWriter(args[1]));
 }

}



 </source>
   
  
 
  



Load a text file contents as a String.

   <source lang="java">
  

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.File; import java.io.FileReader; import java.io.IOException;

public class Main {

 /**
  * Load a text file contents as a String<code>.
  * This method does not perform enconding conversions
  *
  * @param file The input file
  * @return The file contents as a <code>String
  * @exception IOException IO Error
  */
 public static String deserializeString(File file)
 throws IOException {
     int len;
     char[] chr = new char[4096];
     final StringBuffer buffer = new StringBuffer();
     final FileReader reader = new FileReader(file);
     try {
         while ((len = reader.read(chr)) > 0) {
             buffer.append(chr, 0, len);
         }
     } finally {
         reader.close();
     }
     return buffer.toString();
 }

}


 </source>
   
  
 
  



Load File As Text

   <source lang="java">
    

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

/*

* Created on Mar 19, 2005
*/

import java.io.*; /**

* @author J. H. S.
*/

public class IORoutines {

 public static final byte[] LINE_BREAK_BYTES = { (byte) 13, (byte) 10 }; 
 
 public static String loadAsText(InputStream in, String encoding) throws IOException {
   return loadAsText(in, encoding, 4096);
 }
 
 public static String loadAsText(InputStream in, String encoding, int bufferSize) throws IOException {
   InputStreamReader reader = new InputStreamReader(in, encoding);
     char[] buffer = new char[bufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         char[] newBuffer = new char[buffer.length * 2];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = reader.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     return new String(buffer, 0, offset);
 }
 
   public static byte[] load(File file) throws IOException {
       long fileLength = file.length();
       if(fileLength > Integer.MAX_VALUE) {
           throw new IOException("File "" + file.getName() + "" too big");
       }
       InputStream in = new FileInputStream(file);
       try {
         return loadExact(in, (int) fileLength);
       } finally {
           in.close();
       }
   }
   
   public static byte[] load(InputStream in) throws IOException {
       return load(in, 4096);
   }
   public static byte[] load(InputStream in, int initialBufferSize) throws IOException {
     if(initialBufferSize == 0) {
       initialBufferSize = 1;
     }
     byte[] buffer = new byte[initialBufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         int newSize = buffer.length * 2;
         byte[] newBuffer = new byte[newSize];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = in.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     if(offset < buffer.length) {
       byte[] newBuffer = new byte[offset];
       System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
       buffer = newBuffer;
     }
     return buffer;
   }
   
   public static byte[] loadExact(InputStream in, int length) throws IOException {
     byte[] buffer = new byte[length];
     int offset = 0;
     for(;;) {
       int remain = length - offset;
       if(remain <= 0) {
         break;
       }
       int numRead = in.read(buffer, offset, remain);
       if(numRead == -1) {
         throw new IOException("Reached EOF, read " + offset + " expecting " + length);
       }
     offset += numRead;
     }
     return buffer;
   }
   public static boolean equalContent(File file, byte[] content) throws IOException {
     long length = file.length();
     if(length > Integer.MAX_VALUE) {
       throw new IOException("File "" + file + "" too big");
     }
     InputStream in = new FileInputStream(file);
     try {
       byte[] fileContent = loadExact(in, (int) length);
       return java.util.Arrays.equals(content, fileContent);
     } finally {
       in.close();
     }
   }
   
   public static void save(File file, byte[] content) throws IOException {
     FileOutputStream out = new FileOutputStream(file);
     try {
       out.write(content);
     } finally {
       out.close();
     }
   }
   
   /**
    * Reads line without buffering.
    */
   public static String readLine(InputStream in) throws IOException {
     int b;
     StringBuffer sb = null;
     OUTER:
     while((b = in.read()) != -1) {
       if(sb == null) {
         sb = new StringBuffer();
       }
       switch(b) {
         case (byte) "\n":
           break OUTER;
         case (byte) "\r":
           break;
         default:
           sb.append((char) b);
           break;
       }
     }
     return sb == null ? null : sb.toString();
   }
   
   public static void touch(File file) {
     file.setLastModified(System.currentTimeMillis());
   }
   
   public static void saveStrings(File file, java.util.Collection list) throws IOException {
     BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));
     try {
       PrintWriter writer = new PrintWriter(bout);
       java.util.Iterator i = list.iterator();
       while(i.hasNext()) {
         String text = (String) i.next();
         writer.println(text);
       }
       writer.flush();
     } finally {
       bout.close();
     }
   }
   
   public static java.util.List loadStrings(File file) throws IOException {
     java.util.List list = new java.util.LinkedList();
     InputStream in = new FileInputStream(file);
     try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(in));
       String line;
       while((line = reader.readLine()) != null) {
         list.add(line);
       }
       return list;
     } finally {
       in.close();
     }
   }
   

}



 </source>
   
  
 
  



Load file content to List

   <source lang="java">
    

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

/*

* Created on Mar 19, 2005
*/

import java.io.*; /**

* @author J. H. S.
*/

public class IORoutines {

 public static final byte[] LINE_BREAK_BYTES = { (byte) 13, (byte) 10 }; 
 
 public static String loadAsText(InputStream in, String encoding) throws IOException {
   return loadAsText(in, encoding, 4096);
 }
 
 public static String loadAsText(InputStream in, String encoding, int bufferSize) throws IOException {
   InputStreamReader reader = new InputStreamReader(in, encoding);
     char[] buffer = new char[bufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         char[] newBuffer = new char[buffer.length * 2];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = reader.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     return new String(buffer, 0, offset);
 }
 
   public static byte[] load(File file) throws IOException {
       long fileLength = file.length();
       if(fileLength > Integer.MAX_VALUE) {
           throw new IOException("File "" + file.getName() + "" too big");
       }
       InputStream in = new FileInputStream(file);
       try {
         return loadExact(in, (int) fileLength);
       } finally {
           in.close();
       }
   }
   
   public static byte[] load(InputStream in) throws IOException {
       return load(in, 4096);
   }
   public static byte[] load(InputStream in, int initialBufferSize) throws IOException {
     if(initialBufferSize == 0) {
       initialBufferSize = 1;
     }
     byte[] buffer = new byte[initialBufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         int newSize = buffer.length * 2;
         byte[] newBuffer = new byte[newSize];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = in.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     if(offset < buffer.length) {
       byte[] newBuffer = new byte[offset];
       System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
       buffer = newBuffer;
     }
     return buffer;
   }
   
   public static byte[] loadExact(InputStream in, int length) throws IOException {
     byte[] buffer = new byte[length];
     int offset = 0;
     for(;;) {
       int remain = length - offset;
       if(remain <= 0) {
         break;
       }
       int numRead = in.read(buffer, offset, remain);
       if(numRead == -1) {
         throw new IOException("Reached EOF, read " + offset + " expecting " + length);
       }
     offset += numRead;
     }
     return buffer;
   }
   public static boolean equalContent(File file, byte[] content) throws IOException {
     long length = file.length();
     if(length > Integer.MAX_VALUE) {
       throw new IOException("File "" + file + "" too big");
     }
     InputStream in = new FileInputStream(file);
     try {
       byte[] fileContent = loadExact(in, (int) length);
       return java.util.Arrays.equals(content, fileContent);
     } finally {
       in.close();
     }
   }
   
   public static void save(File file, byte[] content) throws IOException {
     FileOutputStream out = new FileOutputStream(file);
     try {
       out.write(content);
     } finally {
       out.close();
     }
   }
   
   /**
    * Reads line without buffering.
    */
   public static String readLine(InputStream in) throws IOException {
     int b;
     StringBuffer sb = null;
     OUTER:
     while((b = in.read()) != -1) {
       if(sb == null) {
         sb = new StringBuffer();
       }
       switch(b) {
         case (byte) "\n":
           break OUTER;
         case (byte) "\r":
           break;
         default:
           sb.append((char) b);
           break;
       }
     }
     return sb == null ? null : sb.toString();
   }
   
   public static void touch(File file) {
     file.setLastModified(System.currentTimeMillis());
   }
   
   public static void saveStrings(File file, java.util.Collection list) throws IOException {
     BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));
     try {
       PrintWriter writer = new PrintWriter(bout);
       java.util.Iterator i = list.iterator();
       while(i.hasNext()) {
         String text = (String) i.next();
         writer.println(text);
       }
       writer.flush();
     } finally {
       bout.close();
     }
   }
   
   public static java.util.List loadStrings(File file) throws IOException {
     java.util.List list = new java.util.LinkedList();
     InputStream in = new FileInputStream(file);
     try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(in));
       String line;
       while((line = reader.readLine()) != null) {
         list.add(line);
       }
       return list;
     } finally {
       in.close();
     }
   }
   

}



 </source>
   
  
 
  



Load file line by line

   <source lang="java">
    

/*

   GNU LESSER GENERAL PUBLIC LICENSE
   Copyright (C) 2006 The Lobo Project
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
   Contact info: lobochief@users.sourceforge.net
  • /

/*

* Created on Mar 19, 2005
*/

import java.io.*; /**

* @author J. H. S.
*/

public class IORoutines {

 public static final byte[] LINE_BREAK_BYTES = { (byte) 13, (byte) 10 }; 
 
 public static String loadAsText(InputStream in, String encoding) throws IOException {
   return loadAsText(in, encoding, 4096);
 }
 
 public static String loadAsText(InputStream in, String encoding, int bufferSize) throws IOException {
   InputStreamReader reader = new InputStreamReader(in, encoding);
     char[] buffer = new char[bufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         char[] newBuffer = new char[buffer.length * 2];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = reader.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     return new String(buffer, 0, offset);
 }
 
   public static byte[] load(File file) throws IOException {
       long fileLength = file.length();
       if(fileLength > Integer.MAX_VALUE) {
           throw new IOException("File "" + file.getName() + "" too big");
       }
       InputStream in = new FileInputStream(file);
       try {
         return loadExact(in, (int) fileLength);
       } finally {
           in.close();
       }
   }
   
   public static byte[] load(InputStream in) throws IOException {
       return load(in, 4096);
   }
   public static byte[] load(InputStream in, int initialBufferSize) throws IOException {
     if(initialBufferSize == 0) {
       initialBufferSize = 1;
     }
     byte[] buffer = new byte[initialBufferSize];
     int offset = 0;
     for(;;) {
       int remain = buffer.length - offset;
       if(remain <= 0) {
         int newSize = buffer.length * 2;
         byte[] newBuffer = new byte[newSize];
         System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
         buffer = newBuffer;
         remain = buffer.length - offset;
       }
         int numRead = in.read(buffer, offset, remain);
         if(numRead == -1) {
           break;
         }
       offset += numRead;
     }
     if(offset < buffer.length) {
       byte[] newBuffer = new byte[offset];
       System.arraycopy(buffer, 0, newBuffer, 0, offset);                    
       buffer = newBuffer;
     }
     return buffer;
   }
   
   public static byte[] loadExact(InputStream in, int length) throws IOException {
     byte[] buffer = new byte[length];
     int offset = 0;
     for(;;) {
       int remain = length - offset;
       if(remain <= 0) {
         break;
       }
       int numRead = in.read(buffer, offset, remain);
       if(numRead == -1) {
         throw new IOException("Reached EOF, read " + offset + " expecting " + length);
       }
     offset += numRead;
     }
     return buffer;
   }
   public static boolean equalContent(File file, byte[] content) throws IOException {
     long length = file.length();
     if(length > Integer.MAX_VALUE) {
       throw new IOException("File "" + file + "" too big");
     }
     InputStream in = new FileInputStream(file);
     try {
       byte[] fileContent = loadExact(in, (int) length);
       return java.util.Arrays.equals(content, fileContent);
     } finally {
       in.close();
     }
   }
   
   public static void save(File file, byte[] content) throws IOException {
     FileOutputStream out = new FileOutputStream(file);
     try {
       out.write(content);
     } finally {
       out.close();
     }
   }
   
   /**
    * Reads line without buffering.
    */
   public static String readLine(InputStream in) throws IOException {
     int b;
     StringBuffer sb = null;
     OUTER:
     while((b = in.read()) != -1) {
       if(sb == null) {
         sb = new StringBuffer();
       }
       switch(b) {
         case (byte) "\n":
           break OUTER;
         case (byte) "\r":
           break;
         default:
           sb.append((char) b);
           break;
       }
     }
     return sb == null ? null : sb.toString();
   }
   
   public static void touch(File file) {
     file.setLastModified(System.currentTimeMillis());
   }
   
   public static void saveStrings(File file, java.util.Collection list) throws IOException {
     BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file));
     try {
       PrintWriter writer = new PrintWriter(bout);
       java.util.Iterator i = list.iterator();
       while(i.hasNext()) {
         String text = (String) i.next();
         writer.println(text);
       }
       writer.flush();
     } finally {
       bout.close();
     }
   }
   
   public static java.util.List loadStrings(File file) throws IOException {
     java.util.List list = new java.util.LinkedList();
     InputStream in = new FileInputStream(file);
     try {
       BufferedReader reader = new BufferedReader(new InputStreamReader(in));
       String line;
       while((line = reader.readLine()) != null) {
         list.add(line);
       }
       return list;
     } finally {
       in.close();
     }
   }
   

}



 </source>
   
  
 
  



Read and return the entire contents of the supplied File.

   <source lang="java">

/*

* JBoss DNA (http://www.jboss.org/dna)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.  Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of 
* individual contributors. 
*
* JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* JBoss DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; /**

* @author Randall Hauch
*/

public class Main {

 /**
  * Read and return the entire contents of the supplied {@link File}.
  * 
  * @param file the file containing the information to be read; may be null
  * @return the contents, or an empty string if the supplied reader is null
  * @throws IOException if there is an error reading the content
  */
 public static String read( File file ) throws IOException {
     if (file == null) return "";
     StringBuilder sb = new StringBuilder();
     boolean error = false;
     Reader reader = new FileReader(file);
     try {
         int numRead = 0;
         char[] buffer = new char[1024];
         while ((numRead = reader.read(buffer)) > -1) {
             sb.append(buffer, 0, numRead);
         }
     } catch (IOException e) {
         error = true; // this error should be thrown, even if there is an error closing reader
         throw e;
     } catch (RuntimeException e) {
         error = true; // this error should be thrown, even if there is an error closing reader
         throw e;
     } finally {
         try {
             reader.close();
         } catch (IOException e) {
             if (!error) throw e;
         }
     }
     return sb.toString();
 }

}

 </source>
   
  
 
  



Searches case sensitively in a file

   <source lang="java">
    

import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; /*

* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2005 Marc Eppelmann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Provides general global file utility methods
*
* @author marc.eppelmann
*/

class FileUtil {

   //~ Constructors ***********************************************************************
   /**
    * Creates a new FileUtil object.
    */
   public FileUtil()
   {
   }
   //~ Methods ****************************************************************************
   /**
    * Gets the content from a File as StringArray List.
    *
    * @param fileName A file to read from.
    * @return List of individual line of the specified file. List may be empty but not
    *         null.
    * @throws IOException
    */
   public static ArrayList getFileContent(String fileName)
           throws IOException
   {
       ArrayList result = new ArrayList();
       File aFile = new File(fileName);
       if (!aFile.isFile())
       {
           //throw new IOException( fileName + " is not a regular File" );
           return result; // None
       }
       BufferedReader reader = null;
       try
       {
           reader = new BufferedReader(new FileReader(aFile));
       }
       catch (FileNotFoundException e1)
       {
           // TODO handle Exception
           e1.printStackTrace();
           return result;
       }
       String aLine = null;
       while ((aLine = reader.readLine()) != null)
       {
           result.add(aLine + "\n");
       }
       reader.close();
       return result;
   }
   /**
    * Searches case sensitively, and returns true if the given SearchString occurs in the
    * first File with the given Filename.
    *
    * @param aFileName     A files name
    * @param aSearchString the string search for
    * @return true if found in the file otherwise false
    */
   public static boolean fileContains(String aFileName, String aSearchString)
   {
       return (fileContains(aFileName, aSearchString, false));
   }
   /**
    * Tests if the given File contains the given Search String
    *
    * @param aFileName             A files name
    * @param aSearchString         the String to search for
    * @param caseInSensitiveSearch If false the Search is casesensitive
    * @return true if found in the file otherwise false
    */
   public static boolean fileContains(String aFileName, String aSearchString,
                                      boolean caseInSensitiveSearch)
   {
       boolean result = false;
       String searchString = caseInSensitiveSearch
               ? aSearchString.toLowerCase() : aSearchString;
       ArrayList fileContent = new ArrayList();
       try
       {
           fileContent = getFileContent(aFileName);
       }
       catch (IOException e)
       {
           // TODO handle Exception
           e.printStackTrace();
       }
       Iterator linesIter = fileContent.iterator();
       while (linesIter.hasNext())
       {
           String currentline = (String) linesIter.next();
           if (caseInSensitiveSearch)
           {
               currentline = currentline.toLowerCase();
           }
           if (currentline.indexOf(searchString) > -1)
           {
               result = true;
               break;
           }
       }
       return result;
   }
   /**
    * Gets file date and time.
    *
    * @param url The URL of the file for which date and time will be returned.
    * @return Returns long value which is the date and time of the file. If any error
    *         occures returns -1 (=no file date and time available).
    */
   public static long getFileDateTime(URL url)
   {
       if (url == null)
       {
           return -1;
       }
       String fileName = url.getFile();
       if (fileName.charAt(0) == "/" || fileName.charAt(0) == "\\")
       {
           fileName = fileName.substring(1, fileName.length());
       }
       try
       {
           File file = new File(fileName);
           // File name must be a file or a directory.
           if (!file.isDirectory() && !file.isFile())
           {
               return -1;
           }
           return file.lastModified();
       }
       catch (java.lang.Exception e)
       {   // Trap all Exception based exceptions and return -1.
           return -1;
       }
   }
   public static String[] getFileNames(String dirPath) throws Exception
   {
       return getFileNames(dirPath, null);
   }
   public static String[] getFileNames(String dirPath, FilenameFilter fileNameFilter) throws Exception
   {
       String fileNames[] = null;
       File dir = new File(dirPath);
       if (dir.isDirectory())
       {
           if (fileNameFilter != null)
           {
               fileNames = dir.list(fileNameFilter);
           }
           else
           {
               fileNames = dir.list();
           }
       }
       return fileNames;
   }
   /**
    * Test main
    *
    * @param args
    */
   public static void main(String[] args)
   {
   }

}



 </source>
   
  
 
  



To Hex String and char

   <source lang="java">
    

/* jcifs smb client library in Java

* Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
*                     "Christopher R. Hertel" <jcifs at samba dot org>
* 
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* 
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

import java.io.OutputStream; import java.io.PrintStream; /**

*/

public class Hexdump {

   private static final String NL = System.getProperty( "line.separator" );
   private static final int NL_LENGTH = NL.length();
   private static final char[] SPACE_CHARS = {
       " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",
       " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",
       " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "
   };
   public static final char[] HEX_DIGITS = { 
       "0", "1", "2", "3", "4", "5",
       "6", "7", "8", "9", "A", "B",
       "C", "D", "E", "F"
   };

/**

* Generate "hexdump" output of the buffer at src like the following:
*
*

 * 00000: 04 d2 29 00 00 01 00 00 00 00 00 01 20 45 47 46  |..)......... EGF|
 * 00010: 43 45 46 45 45 43 41 43 41 43 41 43 41 43 41 43  |CEFEECACACACACAC|
 * 00020: 41 43 41 43 41 43 41 43 41 43 41 41 44 00 00 20  |ACACACACACAAD.. |
 * 00030: 00 01 c0 0c 00 20 00 01 00 00 00 00 00 06 20 00  |..... ........ .|
 * 00040: ac 22 22 e1                                      |."".            |
 * </blockquote>

*/ public static void hexdump( PrintStream ps, byte[] src, int srcIndex, int length ) { if( length == 0 ) { return; } int s = length % 16; int r = ( s == 0 ) ? length / 16 : length / 16 + 1; char[] c = new char[r * (74 + NL_LENGTH)]; char[] d = new char[16]; int i; int si = 0; int ci = 0; do { toHexChars( si, c, ci, 5 ); ci += 5; c[ci++] = ":"; do { if( si == length ) { int n = 16 - s; System.arraycopy( SPACE_CHARS, 0, c, ci, n * 3 ); ci += n * 3; System.arraycopy( SPACE_CHARS, 0, d, s, n ); break; } c[ci++] = " "; i = src[srcIndex + si] & 0xFF; toHexChars( i, c, ci, 2 ); ci += 2; if( i < 0 || Character.isISOControl( (char)i )) { d[si % 16] = "."; } else { d[si % 16] = (char)i; } } while(( ++si % 16 ) != 0 ); c[ci++] = " "; c[ci++] = " "; c[ci++] = "|"; System.arraycopy( d, 0, c, ci, 16 ); ci += 16; c[ci++] = "|"; NL.getChars( 0, NL_LENGTH, c, ci ); ci += NL_LENGTH; } while( si < length ); ps.println( c ); } /** * This is an alternative to the java.lang.Integer.toHexString</cod> * method. It is an efficient relative that also will pad the left side so * that the result is <code>size digits. */ public static String toHexString( int val, int size ) { char[] c = new char[size]; toHexChars( val, c, 0, size ); return new String( c ); } public static String toHexString( long val, int size ) { char[] c = new char[size]; toHexChars( val, c, 0, size ); return new String( c ); } public static String toHexString( byte[] src, int srcIndex, int size ) { char[] c = new char[size]; size = ( size % 2 == 0 ) ? size / 2 : size / 2 + 1; for( int i = 0, j = 0; i < size; i++ ) { c[j++] = HEX_DIGITS[(src[i] >> 4 ) & 0x0F]; if( j == c.length ) { break; } c[j++] = HEX_DIGITS[src[i] & 0x0F]; } return new String( c ); } /** * This is the same as {@link jcifs.util.Hexdump#toHexString(int val, int * size)} but provides a more practical form when trying to avoid {@link * java.lang.String} concatenation and {@link java.lang.StringBuffer}. */ public static void toHexChars( int val, char dst[], int dstIndex, int size ) { while( size > 0 ) { int i = dstIndex + size - 1; if( i < dst.length ) { dst[i] = HEX_DIGITS[val & 0x000F]; } if( val != 0 ) { val >>>= 4; } size--; } } public static void toHexChars( long val, char dst[], int dstIndex, int size ) { while( size > 0 ) { dst[dstIndex + size - 1] = HEX_DIGITS[(int)( val & 0x000FL )]; if( val != 0 ) { val >>>= 4; } size--; } } }



</source>





Writing delimited text data to a file or a stream

<source lang="java">

/* * Java CSV is a stream based library for reading and writing * CSV and other delimited data. * * Copyright (C) Bruce Dunwiddie bruce@csvreader.ru * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.nio.charset.Charset; /** * A stream based writer for writing delimited text data to a file or a stream. */ public class CsvWriter { private PrintWriter outputStream = null; private String fileName = null; private boolean firstColumn = true; private boolean useCustomRecordDelimiter = false; private Charset charset = null; // this holds all the values for switches that the user is allowed to set private UserSettings userSettings = new UserSettings(); private boolean initialized = false; private boolean closed = false; /** * Double up the text qualifier to represent an occurance of the text * qualifier. */ public static final int ESCAPE_MODE_DOUBLED = 1; /** * Use a backslash character before the text qualifier to represent an * occurance of the text qualifier. */ public static final int ESCAPE_MODE_BACKSLASH = 2; /** * Creates a {@link com.csvreader.CsvWriter CsvWriter} object using a file * as the data destination. * * @param fileName * The path to the file to output the data. * @param delimiter * The character to use as the column delimiter. * @param charset * The {@link java.nio.charset.Charset Charset} to use while * writing the data. */ public CsvWriter(String fileName, char delimiter, Charset charset) { if (fileName == null) { throw new IllegalArgumentException("Parameter fileName can not be null."); } if (charset == null) { throw new IllegalArgumentException("Parameter charset can not be null."); } this.fileName = fileName; userSettings.Delimiter = delimiter; this.charset = charset; } /** * Creates a {@link com.csvreader.CsvWriter CsvWriter} object using a file * as the data destination. Uses a comma as the column delimiter and * ISO-8859-1 as the {@link java.nio.charset.Charset Charset}. * * @param fileName * The path to the file to output the data. */ public CsvWriter(String fileName) { this(fileName, Letters.ruMA, Charset.forName("ISO-8859-1")); } /** * Creates a {@link com.csvreader.CsvWriter CsvWriter} object using a Writer * to write data to. * * @param outputStream * The stream to write the column delimited data to. * @param delimiter * The character to use as the column delimiter. */ public CsvWriter(Writer outputStream, char delimiter) { if (outputStream == null) { throw new IllegalArgumentException("Parameter outputStream can not be null."); } this.outputStream = new PrintWriter(outputStream); userSettings.Delimiter = delimiter; initialized = true; } /** * Creates a {@link com.csvreader.CsvWriter CsvWriter} object using an * OutputStream to write data to. * * @param outputStream * The stream to write the column delimited data to. * @param delimiter * The character to use as the column delimiter. * @param charset * The {@link java.nio.charset.Charset Charset} to use while * writing the data. */ public CsvWriter(OutputStream outputStream, char delimiter, Charset charset) { this(new OutputStreamWriter(outputStream, charset), delimiter); } /** * Gets the character being used as the column delimiter. * * @return The character being used as the column delimiter. */ public char getDelimiter() { return userSettings.Delimiter; } /** * Sets the character to use as the column delimiter. * * @param delimiter * The character to use as the column delimiter. */ public void setDelimiter(char delimiter) { userSettings.Delimiter = delimiter; } public char getRecordDelimiter() { return userSettings.RecordDelimiter; } /** * Sets the character to use as the record delimiter. * * @param recordDelimiter * The character to use as the record delimiter. Default is * combination of standard end of line characters for Windows, * Unix, or Mac. */ public void setRecordDelimiter(char recordDelimiter) { useCustomRecordDelimiter = true; userSettings.RecordDelimiter = recordDelimiter; } /** * Gets the character to use as a text qualifier in the data. * * @return The character to use as a text qualifier in the data. */ public char getTextQualifier() { return userSettings.TextQualifier; } /** * Sets the character to use as a text qualifier in the data. * * @param textQualifier * The character to use as a text qualifier in the data. */ public void setTextQualifier(char textQualifier) { userSettings.TextQualifier = textQualifier; } /** * Whether text qualifiers will be used while writing data or not. * * @return Whether text qualifiers will be used while writing data or not. */ public boolean getUseTextQualifier() { return userSettings.UseTextQualifier; } /** * Sets whether text qualifiers will be used while writing data or not. * * @param useTextQualifier * Whether to use a text qualifier while writing data or not. */ public void setUseTextQualifier(boolean useTextQualifier) { userSettings.UseTextQualifier = useTextQualifier; } public int getEscapeMode() { return userSettings.EscapeMode; } public void setEscapeMode(int escapeMode) { userSettings.EscapeMode = escapeMode; } public void setComment(char comment) { userSettings.rument = comment; } public char getComment() { return userSettings.rument; } /** * Whether fields will be surrounded by the text qualifier even if the * qualifier is not necessarily needed to escape this field. * * @return Whether fields will be forced to be qualified or not. */ public boolean getForceQualifier() { return userSettings.ForceQualifier; } /** * Use this to force all fields to be surrounded by the text qualifier even * if the qualifier is not necessarily needed to escape this field. Default * is false. * * @param forceQualifier * Whether to force the fields to be qualified or not. */ public void setForceQualifier(boolean forceQualifier) { userSettings.ForceQualifier = forceQualifier; } /** * Writes another column of data to this record. * * @param content * The data for the new column. * @param preserveSpaces * Whether to preserve leading and trailing whitespace in this * column of data. * @exception IOException * Thrown if an error occurs while writing data to the * destination stream. */ public void write(String content, boolean preserveSpaces) throws IOException { checkClosed(); checkInit(); if (content == null) { content = ""; } if (!firstColumn) { outputStream.write(userSettings.Delimiter); } boolean textQualify = userSettings.ForceQualifier; if (!preserveSpaces && content.length() > 0) { content = content.trim(); } if (!textQualify && userSettings.UseTextQualifier && (content.indexOf(userSettings.TextQualifier) > -1 || content.indexOf(userSettings.Delimiter) > -1 || (!useCustomRecordDelimiter && (content .indexOf(Letters.LF) > -1 || content .indexOf(Letters.CR) > -1)) || (useCustomRecordDelimiter && content .indexOf(userSettings.RecordDelimiter) > -1) || (firstColumn && content.length() > 0 && content .charAt(0) == userSettings.rument) || // check for empty first column, which if on its own line must // be qualified or the line will be skipped (firstColumn && content.length() == 0))) { textQualify = true; } if (userSettings.UseTextQualifier && !textQualify && content.length() > 0 && preserveSpaces) { char firstLetter = content.charAt(0); if (firstLetter == Letters.SPACE || firstLetter == Letters.TAB) { textQualify = true; } if (!textQualify && content.length() > 1) { char lastLetter = content.charAt(content.length() - 1); if (lastLetter == Letters.SPACE || lastLetter == Letters.TAB) { textQualify = true; } } } if (textQualify) { outputStream.write(userSettings.TextQualifier); if (userSettings.EscapeMode == ESCAPE_MODE_BACKSLASH) { content = replace(content, "" + Letters.BACKSLASH, "" + Letters.BACKSLASH + Letters.BACKSLASH); content = replace(content, "" + userSettings.TextQualifier, "" + Letters.BACKSLASH + userSettings.TextQualifier); } else { content = replace(content, "" + userSettings.TextQualifier, "" + userSettings.TextQualifier + userSettings.TextQualifier); } } else if (userSettings.EscapeMode == ESCAPE_MODE_BACKSLASH) { content = replace(content, "" + Letters.BACKSLASH, "" + Letters.BACKSLASH + Letters.BACKSLASH); content = replace(content, "" + userSettings.Delimiter, "" + Letters.BACKSLASH + userSettings.Delimiter); if (useCustomRecordDelimiter) { content = replace(content, "" + userSettings.RecordDelimiter, "" + Letters.BACKSLASH + userSettings.RecordDelimiter); } else { content = replace(content, "" + Letters.CR, "" + Letters.BACKSLASH + Letters.CR); content = replace(content, "" + Letters.LF, "" + Letters.BACKSLASH + Letters.LF); } if (firstColumn && content.length() > 0 && content.charAt(0) == userSettings.rument) { if (content.length() > 1) { content = "" + Letters.BACKSLASH + userSettings.rument + content.substring(1); } else { content = "" + Letters.BACKSLASH + userSettings.rument; } } } outputStream.write(content); if (textQualify) { outputStream.write(userSettings.TextQualifier); } firstColumn = false; } /** * Writes another column of data to this record. Does not preserve * leading and trailing whitespace in this column of data. * * @param content * The data for the new column. * @exception IOException * Thrown if an error occurs while writing data to the * destination stream. */ public void write(String content) throws IOException { write(content, false); } public void writeComment(String commentText) throws IOException { checkClosed(); checkInit(); outputStream.write(userSettings.rument); outputStream.write(commentText); if (useCustomRecordDelimiter) { outputStream.write(userSettings.RecordDelimiter); } else { outputStream.println(); } firstColumn = true; } /** * Writes a new record using the passed in array of values. * * @param values * Values to be written. * * @param preserveSpaces * Whether to preserver leading and trailing spaces in columns * while writing out to the record or not. * * @throws IOException * Thrown if an error occurs while writing data to the * destination stream. */ public void writeRecord(String[] values, boolean preserveSpaces) throws IOException { if (values != null && values.length > 0) { for (int i = 0; i < values.length; i++) { write(values[i], preserveSpaces); } endRecord(); } } /** * Writes a new record using the passed in array of values. * * @param values * Values to be written. * * @throws IOException * Thrown if an error occurs while writing data to the * destination stream. */ public void writeRecord(String[] values) throws IOException { writeRecord(values, false); } /** * Ends the current record by sending the record delimiter. * * @exception IOException * Thrown if an error occurs while writing data to the * destination stream. */ public void endRecord() throws IOException { checkClosed(); checkInit(); if (useCustomRecordDelimiter) { outputStream.write(userSettings.RecordDelimiter); } else { outputStream.println(); } firstColumn = true; } /** * */ private void checkInit() throws IOException { if (!initialized) { if (fileName != null) { outputStream = new PrintWriter(new OutputStreamWriter( new FileOutputStream(fileName), charset)); } initialized = true; } } /** * Clears all buffers for the current writer and causes any buffered data to * be written to the underlying device. */ public void flush() { outputStream.flush(); } /** * Closes and releases all related resources. */ public void close() { if (!closed) { close(true); closed = true; } } /** * */ private void close(boolean closing) { if (!closed) { if (closing) { charset = null; } try { if (initialized) { outputStream.close(); } } catch (Exception e) { // just eat the exception } outputStream = null; closed = true; } } /** * */ private void checkClosed() throws IOException { if (closed) { throw new IOException( "This instance of the CsvWriter class has already been closed."); } } /** * */ protected void finalize() { close(false); } private class Letters { public static final char LF = "\n"; public static final char CR = "\r"; public static final char QUOTE = """; public static final char COMMA = ","; public static final char SPACE = " "; public static final char TAB = "\t"; public static final char POUND = "#"; public static final char BACKSLASH = "\\"; public static final char NULL = "\0"; } private class UserSettings { // having these as publicly accessible members will prevent // the overhead of the method call that exists on properties public char TextQualifier; public boolean UseTextQualifier; public char Delimiter; public char RecordDelimiter; public char Comment; public int EscapeMode; public boolean ForceQualifier; public UserSettings() { TextQualifier = Letters.QUOTE; UseTextQualifier = true; Delimiter = Letters.ruMA; RecordDelimiter = Letters.NULL; Comment = Letters.POUND; EscapeMode = ESCAPE_MODE_DOUBLED; ForceQualifier = false; } } public static String replace(String original, String pattern, String replace) { final int len = pattern.length(); int found = original.indexOf(pattern); if (found > -1) { StringBuffer sb = new StringBuffer(); int start = 0; while (found != -1) { sb.append(original.substring(start, found)); sb.append(replace); start = found + len; found = original.indexOf(pattern, start); } sb.append(original.substring(start)); return sb.toString(); } else { return original; } } }



</source>