Java Text File Read fileAsString(File file)

Here you can find the source of fileAsString(File file)

Description

reads a File as one single string.

License

Open Source License

Parameter

Parameter Description
file the file

Return

the string

Declaration

public static String fileAsString(File file) 

Method Source Code

//package com.java2s;
/*//from   w ww. j av a 2  s  . c  o  m
 * (c) 2012 Michael Schwartz e.U.
 * All Rights Reserved.
 * 
 * This program is not a free software. The owner of the copyright
 * can license the software for you. You may not use this file except in
 * compliance with the License. In case of questions please
 * do not hesitate to contact us at idx@mschwartz.eu.
 * 
 * Filename: FileUtil.java
 * Created: 30.05.2012
 * 
 * Author: $LastChangedBy$
 * Date: $LastChangedDate$
 * Revision: $LastChangedRevision$
 */

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {
    private static final int defaultBlockSize = 8 * 1024;
    /**
     * The Unix separator character.
     */
    private static final char UNIX_SEPARATOR = '/';
    /**
     * The Windows separator character.
     */
    private static final char WINDOWS_SEPARATOR = '\\';

    /**
     * reads a File as one single string.
     * 
     * @param file
     *            the file
     * @return the string
     */
    public static String fileAsString(File file) {
        byte[] content = fileAsByteArray(file);
        if (content == null)
            return "";
        return new String(content);
    }

    public static String fileAsString(RandomAccessFile raf) {
        byte[] content = fileAsByteArray(raf);
        if (content == null)
            return "";
        return new String(content);
    }

    /**
     * reads the whole content of a file denoted by the parameter
     * <code>file</code> as byte array.
     * 
     * @param file
     *            the file
     * @return the byte[]
     */
    public static byte[] fileAsByteArray(File file) {
        byte[] content = new byte[(int) file.length()];
        RandomAccessFile in = null;
        try {
            in = new RandomAccessFile(file, "r");
            int read = 0;
            do {
                int offset = 0;
                read = in.read(content, offset, content.length - offset);
                offset += read;
            } while (read != -1);
        } catch (IOException e) {
            return null;
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    return null;
                }
        }
        return content;
    }

    /**
     * reads the whole content of a file
     * as byte array.
     * 
     * @param snap
     *            the archive file [snap.zip]
     * @param relativePath
     *            the relative path of the file in archive file
     * @return the byte[]
     */
    public static byte[] fileAsByteArray(File snap, String relativePath) throws Exception {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(snap));
        ZipEntry entry;
        byte[] b = null;
        String path = relativePath.replaceAll("\\\\", "/");
        while ((entry = zin.getNextEntry()) != null) {

            String entryName = entry.getName().replaceAll("\\\\", "/");

            if (entryName.equals(path)) {

                ByteArrayOutputStream output = new ByteArrayOutputStream();

                byte[] buffer = new byte[defaultBlockSize];

                int read;
                while (-1 != (read = zin.read(buffer))) {
                    output.write(buffer, 0, read);
                }

                output.close();

                b = output.toByteArray();

                break;

            }

            zin.closeEntry();

        }

        zin.close();

        return b;
    }

    private static byte[] fileAsByteArray(RandomAccessFile raf) {
        byte[] content;
        try {
            content = new byte[(int) raf.length()];
            int read = 0;
            do {
                int offset = 0;
                read = raf.read(content, offset, content.length - offset);
                offset += read;
            } while (read != -1);
        } catch (IOException e) {
            return null;
        }
        return content;
    }

    /**
      * Gets the name minus the path from a full filename.
      * <p>
      * This method will handle a file in either Unix or Windows format.
      * The text after the last forward or backslash is returned.
      * <pre>
      * a/b/c.txt --> c.txt
      * a.txt     --> a.txt
      * a/b/c     --> c
      * a/b/c/    --> ""
      * </pre>
      * <p>
      * The output will be the same irrespective of the machine that the code is running on.
      *
      * @param filename  the filename to query, null returns null
      * @return the name of the file without the path, or an empty string if none exists
      */
    public static String getName(String filename) {
        if (filename == null) {
            return null;
        }
        int index = indexOfLastSeparator(filename);
        return filename.substring(index + 1);
    }

    /**
     * Returns the index of the last directory separator character.
     * <p>
     * This method will handle a file in either Unix or Windows format.
     * The position of the last forward or backslash is returned.
     * <p>
     * The output will be the same irrespective of the machine that the code is running on.
     * 
     * @param filename  the filename to find the last path separator in, null returns -1
     * @return the index of the last separator character, or -1 if there
     * is no such character
     */
    public static int indexOfLastSeparator(String filename) {
        if (filename == null) {
            return -1;
        }
        int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
        int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
        return Math.max(lastUnixPos, lastWindowsPos);
    }
}

Related

  1. fileAsString(String fileName)
  2. fileAsString(String filePath)
  3. fileContentsToString(File errFile)
  4. fileContentsToString(String file)