Java Tutorial/File/Text File

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

Dump a String to a text file with encoding.

/*
 * 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 <code>String</code> 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();
      }
  }
}





Gets the content from a File as String Array List

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)
    {
    }
}





Load a text file contents as a String.

/*
 * 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 <code>String<code>.
   * This method does not perform enconding conversions
   *
   * @param file The input file
   * @return The file contents as a <code>String</code>
   * @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();
  }
}





Load File As Text

/*
    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();
      }
    }
    
}





Load file content to List

/*
    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();
      }
    }
    
}





Load file line by line

/*
    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();
      }
    }
    
}





Read and return the entire contents of the supplied File.

/*
 * 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();
  }
}





Read ByteArrayInputStream to String

import java.io.ByteArrayInputStream;
/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the "License").  You may not use this file except 
 * in compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt or 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html. 
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * HEADER in each file and include the License file at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
 * add the following below this CDDL HEADER, with the 
 * fields enclosed by brackets "[]" replaced with your 
 * own identifying information: Portions Copyright [yyyy] 
 * [name of copyright owner]
 */
/*
 * @(#)ASCIIUtility.java  1.10 05/08/29
 *
 * Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
 */
public class Utils {
  public static String toString(ByteArrayInputStream is) {
    int size = is.available();
    char[] theChars = new char[size];
    byte[] bytes    = new byte[size];
    is.read(bytes, 0, size);
    for (int i = 0; i < size;)
        theChars[i] = (char)(bytes[i++]&0xff);
    
    return new String(theChars);
      }
}





ReadLines: read file to list of strings

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Utils {
  public static List<String> readLines(File file) throws Exception {
      if (!file.exists()) {
          return new ArrayList<String>();
      }
      BufferedReader reader = new BufferedReader(new FileReader(file));
      List<String> results = new ArrayList<String>();
      String line = reader.readLine();
      while (line != null) {
          results.add(line);
          line = reader.readLine();
      }
      return results;
  }
}





Read string from InputStream and Reader

/*
 * $RCSfile: StringIO.java,v $
 *
 * Copyright (c) 2007 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:
 *
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistribution 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.
 *
 * 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 MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
 * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
 * USING, MODIFYING OR DISTRIBUTING THIS 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 THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or
 * intended for use in the design, construction, operation or
 * maintenance of any nuclear facility.
 *
 * $Revision: 1.4 $
 * $Date: 2007/02/09 17:20:42 $
 * $State: Exp $
 */
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
/**
 * Utility class with static methods to read the entire contents of a
 * file, URL, InputStream, or Reader into a single String that is
 * returned to the user.
 *
 * @since Java 3D 1.4
 */
public class StringIO {
    /**
     * Read the entire contents of the specified file and return a
     * single String object containing the contents of the file.
     *
     * @param fileName the name of the file from which to read
     *
     * @return a String containing the contents of the input file
     *
     * @throws IOException if the specified file cannot be opened, or
     * if an I/O error occurs while reading the file
     */
    public static String readFully(String fileName) throws IOException {
  return readFully(new File(fileName));
    }
    /**
     * Read the entire contents of the specified file and return a
     * single String object containing the contents of the file.
     * This method does not return until the end of the input file
     * is reached.
     *
     * @param file a File from which to read
     *
     * @return a String containing the contents of the input file
     *
     * @throws IOException if the specified file cannot be opened, or
     * if an I/O error occurs while reading the file
     */
    public static String readFully(File file) throws IOException {
  return readFully(new FileReader(file));
    }
    /**
     * Read the entire contents of the specified URL and return a
     * single String object containing the contents of the URL.
     * This method does not return until an end of stream is reached
     * for the URL.
     *
     * @param url a URL from which to read
     *
     * @return a String containing the contents of the input URL
     *
     * @throws IOException if the specified URL cannot be opened, or
     * if an I/O error occurs while reading the URL
     */
    public static String readFully(URL url) throws IOException {
  return readFully(url.openStream());
    }
    /**
     * Read the entire contents of the specified InputStream and return a
     * single String object containing the contents of the InputStream.
     * This method does not return until the end of the input
     * stream is reached.
     *
     * @param stream an InputStream from which to read
     *
     * @return a String containing the contents of the input stream
     *
     * @throws IOException if an I/O error occurs while reading the input stream
     */
    public static String readFully(InputStream stream) throws IOException {
  return readFully(new InputStreamReader(stream));
    }
    /**
     * Read the entire contents of the specified Reader and return a
     * single String object containing the contents of the InputStream.
     * This method does not return until the end of the input file or
     * stream is reached.
     *
     * @param reader a Reader from which to read
     *
     * @return a String containing the contents of the stream
     *
     * @throws IOException if an I/O error occurs while reading the input stream
     */
    public static String readFully(Reader reader) throws IOException {
  char[] arr = new char[8*1024]; // 8K at a time
  StringBuffer buf = new StringBuffer();
  int numChars;
  while ((numChars = reader.read(arr, 0, arr.length)) > 0) {
      buf.append(arr, 0, numChars);
  }
  return buf.toString();
    }

    /**
     * Do not construct an instance of this class.
     */
    private StringIO() {
    }
}





Read the contents of a file and place them in a string object.

/*
 * 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;

/**
 *
 *  @author 
 *  @version $Id: StringUtils.java 685685 2008-08-13 21:43:27Z nbubna $
 */
public class Main {

  /**
   * Read the contents of a file and place them in
   * a string object.
   *
   * @param file path to file.
   * @return String contents of the file.
   */
  public static String fileContentsToString(String file)
  {
      String contents = "";
      File f = null;
      try
      {
          f = new File(file);
          if (f.exists())
          {
              FileReader fr = null;
              try
              {
                  fr = new FileReader(f);
                  char[] template = new char[(int) f.length()];
                  fr.read(template);
                  contents = new String(template);
              }
              catch (Exception e)
              {
                  e.printStackTrace();
              }
              finally
              {
                  if (fr != null)
                  {
                      fr.close();
                  }
              }
          }
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
      return contents;
  }
}





Searches case sensitively in a file

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)
    {
    }
}