1   /*
2    * CharacterCounter
3    * Copyright (C) 2008 Christian Schenk
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    * 
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   * 
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18   */
19  package org.christianschenk.cc.util;
20  
21  import java.io.File;
22  import java.io.FileInputStream;
23  import java.io.FilenameFilter;
24  import java.io.InputStream;
25  import java.util.ArrayList;
26  import java.util.List;
27  import java.util.Scanner;
28  
29  /**
30   * Some file utils.
31   * 
32   * @author Christian Schenk
33   */
34  public class FileHelper {
35  
36  	/**
37  	 * Returns files in a directory ignoring dot files.
38  	 */
39  	public static List<String> getFilesInDirectory(final String dirname) {
40  		final File dir = new File(dirname);
41  		if (dir.isDirectory() == false) throw new RuntimeException("This is not a directory '" + dirname + "'");
42  		final List<String> filenames = new ArrayList<String>();
43  		for (final File file : dir.listFiles(new IgnoreDotFilesFilter())) {
44  			filenames.add(file.getAbsolutePath());
45  		}
46  		return filenames;
47  	}
48  
49  	private static class IgnoreDotFilesFilter implements FilenameFilter {
50  		public boolean accept(final File dir, final String name) {
51  			return name.startsWith(".") == false;
52  		}
53  	}
54  
55  	/**
56  	 * Reads a file into a string.
57  	 */
58  	public static String readFile(final String filename) {
59  		final StringBuilder buf = new StringBuilder();
60  		try {
61  			final InputStream input = (filename.startsWith("/")) ? new FileInputStream(filename) : FileHelper.class.getClassLoader().getResourceAsStream(filename);
62  			final Scanner scan = new Scanner(input);
63  			while (scan.hasNextLine()) {
64  				buf.append(scan.nextLine() + System.getProperty("line.separator"));
65  			}
66  		} catch (final Exception ex) {
67  			throw new RuntimeException(ex);
68  		}
69  		return buf.toString();
70  	}
71  }