View Javadoc

1   /*
2    * JBoss, Home of Professional Open Source.
3    * Copyright 2013, Red Hat Middleware LLC, and individual contributors
4    * as indicated by the @author tags. See the copyright.txt file in the
5    * distribution for a full listing of individual contributors.
6    *
7    * This is free software; you can redistribute it and/or modify it
8    * under the terms of the GNU Lesser General Public License as
9    * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */
22  package org.redhat.vmtruckloader.util;
23  
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileNotFoundException;
27  import java.io.FileOutputStream;
28  import java.io.IOException;
29  import java.io.InputStreamReader;
30  import java.io.OutputStreamWriter;
31  import java.io.Reader;
32  import java.io.Writer;
33  import java.util.ArrayList;
34  import java.util.List;
35  import java.util.Scanner;
36  
37  /**
38   * 
39   * @author Romain Pelisse - romain@redhat.com
40   *
41   */
42  public final class FileUtils {
43  
44  	private final static String DEFAULT_FILE_ENCODING = "UTF-8";
45  	
46  	private FileUtils() {}
47  	
48  	public static Reader constructReaderFromClasspathResource(final String filename) {
49  		try {
50  			return new InputStreamReader(FileUtils.getClassLoader().getResourceAsStream(filename));
51  		} catch ( Exception e) {
52  			final String errorMssg = "Can't read file " + filename + " from classloader.";
53  			throw new IllegalStateException(errorMssg,e);
54  		}		
55  	}
56  	
57  	private static ClassLoader getClassLoader() {
58  		return Thread.currentThread().getContextClassLoader();
59  	}
60  
61  	public static String getFileEncoding() {
62          String fileEncoding = System.getProperty("file.encoding");
63          if ( fileEncoding == null || "".equals(fileEncoding))
64           	fileEncoding = DEFAULT_FILE_ENCODING;       	// Fallback to UTF-8 default encoding
65          return fileEncoding;
66  	}
67  
68  	public static boolean exists(String filename) {
69  		return new File(filename).exists();
70  	}
71  
72      public static void write(String filename, String text) {
73          String fileEncoding = FileUtils.getFileEncoding();
74          Writer out = null;
75          try {
76          	out = new OutputStreamWriter(new FileOutputStream(filename), fileEncoding);
77              out.write(text);
78              out.flush();
79  			if (out != null )
80  				out.close();
81          } catch (IOException e) {
82  			throw new IllegalStateException(e);
83  		}
84      }
85      
86      public static String read(String fileName) {
87          String fileEncoding = getFileEncoding();
88          StringBuilder text = new StringBuilder();
89  
90          Scanner scanner = null;
91          try {
92              scanner = new Scanner(new FileInputStream(fileName), fileEncoding);
93              while (scanner.hasNextLine()) {
94                  text.append(scanner.nextLine());
95              }
96          } catch (FileNotFoundException e) {
97          	throw new IllegalStateException(e);
98  		} finally {
99          	if ( scanner != null )
100         		scanner.close();
101         }
102         return text.toString();
103     }
104 	
105 
106     public static List<String> readLineByLine(File file) {
107     	if ( file == null )
108     		throw new IllegalArgumentException("Provided was file object was 'null'");
109     	if ( ! file.exists())
110     		throw new IllegalArgumentException("File " + file.getAbsolutePath() + " does not exist");
111     	if ( ! file.canRead() )
112     		throw new IllegalArgumentException("File " + file.getAbsolutePath() + " can't be read");
113 
114     	return readLineByLine(file.getAbsoluteFile().toString());
115     }
116 
117     public static List<String> readLineByLine(String fileName) {
118         String fileEncoding = getFileEncoding();        
119         List<String> lines = new ArrayList<String>();
120         Scanner scanner = null;
121         try {
122             scanner = new Scanner(new FileInputStream(fileName), fileEncoding);
123             while (scanner.hasNextLine()) {
124             	lines.add(scanner.nextLine());
125             }
126         } catch (FileNotFoundException e) {
127         	throw new IllegalStateException(e);
128 		} finally {
129         	if ( scanner != null )
130         		scanner.close();
131         }
132         return lines;
133     }
134 
135     
136 	public static void delete(String outputFilename) {
137 		final File file = new File(outputFilename);
138 		if ( file.exists() && file.canWrite() && file.isFile() ) file.delete();
139 	}
140 }