Java BufferedReader Read readFileAsHash(File file)

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

Description

read File As Hash

License

Open Source License

Declaration

public static HashMap<String, String> readFileAsHash(File file) throws Exception 

Method Source Code

//package com.java2s;
/**/*w  w  w .ja  v a  2  s . co  m*/
 * Copyright (c) 2004-2006 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors: 
 *   IBM - Initial API and implementation
 */

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

import java.util.HashMap;

public class Main {
    public static HashMap<String, String> readFileAsHash(File file) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        HashMap<String, String> pairs = new HashMap<String, String>();
        try {
            BufferedReader in = new BufferedReader(new FileReader(file));
            try {
                int size = 0;
                char[] buff = new char[512];
                while ((size = in.read(buff)) >= 0) {
                    stringBuffer.append(buff, 0, size);
                }
            } finally {
                in.close();
            }
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }

        int length = stringBuffer.length();
        if (length > 0) {
            String[] namesAndValues = (stringBuffer.toString() + "\n").replaceAll("\\r\\n", "\n")
                    .split("[\\n|\\r]");
            for (int i = 0; i < namesAndValues.length; i++) {
                String[] pair = namesAndValues[i].split("=");
                if (pair.length > 0 && pair[0] != null) {
                    pairs.put(pair[0], pair.length > 1 && pair[1] != null ? pair[1] : "");
                }
            }
        }
        return pairs;
    }
}

Related

  1. readFile(String path)
  2. readFile(String pathname)
  3. readFile(String sFileName_)
  4. readFile(String uri)
  5. readFile(String xmlFile)
  6. readFileAsLines(File fileLocation)
  7. readFileAsLines(String aFile)
  8. readFileAsList(final String filename)
  9. readFileAsList(String filename, String splitter)