001/**
002 * Copyright (C) 2007 - 2016, Jens Lehmann
003 *
004 * This file is part of DL-Learner.
005 *
006 * DL-Learner is free software; you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation; either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * DL-Learner is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
018 */
019package org.dllearner.utilities;
020
021import java.io.BufferedInputStream;
022import java.io.BufferedOutputStream;
023import java.io.BufferedReader;
024import java.io.File;
025import java.io.FileInputStream;
026import java.io.FileOutputStream;
027import java.io.FileReader;
028import java.io.IOException;
029import java.io.InputStreamReader;
030import java.io.ObjectInputStream;
031import java.io.ObjectOutputStream;
032import java.net.URL;
033import java.nio.charset.Charset;
034import java.util.ArrayList;
035import java.util.List;
036import java.util.StringTokenizer;
037
038import com.google.common.io.FileWriteMode;
039import org.slf4j.Logger;
040import org.slf4j.LoggerFactory;
041
042import com.google.common.base.Charsets;
043
044/**
045 * @author Jens Lehmann
046 * 
047 */
048public class Files {
049
050        private static final Logger logger = LoggerFactory.getLogger(Files.class);
051        
052        public static boolean debug = false;
053
054        /**
055         * Reads input from a URL and stores it in a string (only recommend for small files).
056         * @param file URL of a file.
057         * @return Contents of the file.
058         * @throws IOException URL not accessible or content cannot be read for some reason.
059         */
060        public static String readFile(URL file) throws IOException {
061                 BufferedReader in = new BufferedReader(new InputStreamReader(file.openStream()));
062
063                StringBuilder input = new StringBuilder();
064                String inputLine;
065                while ((inputLine = in.readLine()) != null) {
066                    input.append(inputLine).append("\n");
067                }
068                in.close();
069                            
070                return input.toString();
071        }
072        
073        /**
074         * Reads in a file.
075         * 
076         * @param file
077         *            The file to read.
078         * @return Content of the file.
079         */
080        public static String readFile(File file) throws IOException {
081
082                StringBuilder content = new StringBuilder();
083                try (BufferedReader br = new BufferedReader(new FileReader(file))) {
084                        String line;
085
086                        while ((line = br.readLine()) != null) {
087                                content.append(line);
088                                content.append(System.getProperty("line.separator"));
089                        }
090                }
091                return content.toString();
092                
093        }
094        
095        /**
096         * Reads in a file as Array
097         * 
098         * @param file
099         *            The file to read.
100         * @return StringArray with lines
101         */
102        public static String[] readFileAsArray(File file) throws IOException {
103                String content = readFile(file);
104                StringTokenizer st = new StringTokenizer(content, System.getProperty("line.separator"));
105                List<String> l = new ArrayList<>();
106                while (st.hasMoreTokens()) {
107                        l.add(st.nextToken());
108                        
109                }
110                
111                return l.toArray(new String[l.size()]);
112                
113        }
114        
115        /**
116         * writes a serializable Object to a File.
117         * @param obj the object
118         * @param file the file
119         */
120        public static void writeObjectToFile(Object obj, File file){
121                
122                ObjectOutputStream oos = null;
123                try{
124                        FileOutputStream fos = new FileOutputStream(file);
125                        BufferedOutputStream bos = new BufferedOutputStream(fos);
126                        oos = new ObjectOutputStream(bos);
127                        
128                        oos.writeObject(obj);
129                        oos.flush();
130                        oos.close();
131                        }catch (Exception e) {
132                                 e.printStackTrace();
133                        }finally{
134                                try{
135                                        oos.close();
136                                }catch (Exception e) {
137                                         e.printStackTrace();
138                                }
139                        }
140        }
141        
142        public static Object readObjectfromFile( File file){
143                ObjectInputStream ois = null;
144                try{
145                        FileInputStream fis = new FileInputStream(file);
146                        BufferedInputStream bis = new BufferedInputStream(fis);
147                        ois = new ObjectInputStream(bis);
148                        return ois.readObject();
149                }catch (Exception e) {
150                         e.printStackTrace();
151                }finally{
152                        try {
153                                ois.close();
154                        } catch (Exception e) {
155                                e.printStackTrace();
156                        }
157                        
158                }
159                return null;
160        }
161                
162
163        /**
164         * Creates a new file with the given content or replaces the content of a
165         * file.
166         * 
167         * @param file
168         *            The file to use.
169         * @param content
170         *            Content of the file.
171         */
172        public static void createFile(File file, String content) {
173                File parentFile = file.getParentFile();
174                if (parentFile != null) { parentFile.mkdirs(); }
175                try {
176                        com.google.common.io.Files.asCharSink(file, Charsets.UTF_8).write(content);
177                } catch (IOException e) {
178                        logger.error("Failed to write content to file " + file, e);
179                }
180        }
181
182        /**
183         * Appends content to a file.
184         * 
185         * @param file
186         *            The file to create.
187         * @param content
188         *            Content of the file.
189         */
190        public static void appendToFile(File file, String content) {
191                try {
192                        com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND).write(content);
193                } catch (IOException e) {
194                        logger.error("Failed to append content to file " + file, e);
195                }
196        }
197
198        /**
199         * Write content to a file.
200         *
201         * @param file
202         *            The file to create.
203         * @param content
204         *            Content of the file.
205         */
206        public static void writeToFile(String content, File file) throws IOException {
207                java.nio.file.Files.write(file.toPath(), content.getBytes());
208        }
209        
210        public static void clearFile(File file) {
211                try{
212                createFile(file, "");
213                }catch (Exception e) {
214                        e.printStackTrace();
215                        if(debug){System.exit(0);}
216                }
217        }
218        
219        
220        public static void deleteFile(String file) {
221                deleteFile(new File(file));
222        }
223        
224        public static void deleteFile(File file) {
225                
226                try{
227                        file.delete();
228                }catch (Exception e) {
229                        e.printStackTrace();
230                        if(debug){System.exit(0);}
231                }
232        }
233        
234        public static void mkdir(String dir){
235                if (!new File(dir).exists()) {
236                        try{
237                        new File(dir).mkdir();
238                        }catch (Exception e) {
239                                e.printStackTrace();
240                                if(debug){System.exit(0);}
241                                // this should not be a show stopper
242                        }
243                }
244        }
245        
246
247}