summaryrefslogtreecommitdiff
path: root/source/com/c2kernel/utils/FileStringUtility.java
blob: 843a44e846c70523bbe35539702f4d0dab85865b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package com.c2kernel.utils;

//Java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;

/**************************************************************************
 *
 * @author $Author: abranson $ $Date: 2004/10/20 14:10:21 $
 * @version $Revision: 1.31 $
 **************************************************************************/
public class FileStringUtility
{
	/**************************************************************************
	 * Reads a file and converts it to String
	 **************************************************************************/
	static public String file2String(File file) throws FileNotFoundException, IOException
	{
		FileInputStream fis = new FileInputStream(file);
		byte[] bArray = (byte[]) Array.newInstance(byte.class, (int) file.length());
		Logger.msg(8, "FileStringUtility.file2String() - Reading file '" + file.getAbsolutePath()+"'");

		fis.read(bArray, 0, (int) file.length());
		fis.close();

		Logger.msg(9, "FileStringUtility.file2String() - file '" + file.getAbsolutePath() + "' read.");

		return new String(bArray);
	}

	/**************************************************************************
	 * Reads a file and converts it to String
	 **************************************************************************/
	static public String file2String(String fileName) throws FileNotFoundException, IOException
	{
		return file2String(new File(fileName));
	}

	/**************************************************************************
	 * Reads a file and converts it to String
	 **************************************************************************/
	static public String url2String(java.net.URL location) throws IOException
	{
		String resource = "";

		BufferedInputStream file = new BufferedInputStream(location.openStream());
		byte[] buffer = new byte[file.available()];

		if (file.read(buffer) > 0)
			resource = new String(buffer);

		file.close();

		return resource;
	}

	/**************************************************************************
	 * Reads a file and converts each line to String[]
	 **************************************************************************/
	static public String[] file2StringArray(File file) throws FileNotFoundException, IOException
	{
		FileReader fr = new FileReader(file);
		BufferedReader buf = new BufferedReader(fr);
		Vector<String> lines = new Vector<String>();
		String thisLine = null;
		while ((thisLine = buf.readLine()) != null)
			lines.addElement(thisLine);
		String[] lineArray = new String[lines.size()];
		for (int i = 0; i < lines.size(); i++)
			lineArray[i] = lines.get(i);
		return lineArray;
	}

	/**************************************************************************
	 * Reads a file and converts it to String[]
	 **************************************************************************/
	static public String[] file2StringArray(String fileName) throws FileNotFoundException, IOException
	{
		return file2StringArray(new File(fileName));
	}

	/**************************************************************************
	 * Saves a string to a text file
	 **************************************************************************/
	static public void string2File(File file, String data) throws FileNotFoundException, IOException
	{
		FileWriter thisFile = new FileWriter(file);
		BufferedWriter thisFileBuffer = new BufferedWriter(thisFile);

		Logger.msg(9, "FileStringUtility.string2File() - writing file '" + file.getAbsolutePath()+"'");

		thisFileBuffer.write(data);
		thisFileBuffer.close();

		Logger.msg(9, "FileStringUtility.string2File() - file '" + file.getAbsolutePath() + "' complete.");
	}

	/**************************************************************************
	 * Saves a string to a text file
	 **************************************************************************/
	static public void string2File(String fileName, String data) throws FileNotFoundException, IOException
	{
		string2File(new File(fileName), data);
	}

	/**************************************************************************
	 * checks for existing directory
	 **************************************************************************/
	static public boolean checkDir(String dirPath)
	{
		File dir = new File(dirPath);

		if (dir.isFile())
		{
			Logger.error("FileStringUtility.checkDir() - '" + dir.getAbsolutePath() + "' is a file.");
			return false;
		}
		else if (!dir.exists())
		{
			Logger.msg(9, "FileStringUtility.checkDir() - directory '" + dir.getAbsolutePath() + "' does not exist.");
			return false;
		}

		return true;
	}

	/**************************************************************************
	 * creating a new directory
	 **************************************************************************/
	static public boolean createNewDir(String dirPath)
	{
		File dir = new File(dirPath);

		if (dir.isFile())
		{
			Logger.error("FileStringUtility.createNewDir() - '" + dir.getAbsolutePath() + "' is a file.");
			return false;
		}
		else if (dir.exists())
		{
			Logger.msg(8, "FileStringUtility.createNewDir() - '" + dir.getAbsolutePath() + "' already exists.");
			return false;
		}
		else
		{
			if (!dir.mkdirs())
			{
				Logger.error("FileStringUtility - Could not create new directory '" + dir.getAbsolutePath() + "'");
				return false;
			}
		}
		return true;
	}

	/**************************************************************************
	 * deleting a existing directory
	 **************************************************************************/
	static public boolean deleteDir(String dirPath)
	{
		File dir = new File(dirPath);

		if (!checkDir(dirPath))
		{
			Logger.msg(8, "FileStringUtility.deleteDir() - directory '" + dir.getAbsolutePath() + "' does not exist.");
			return false;
		}

		if (!dir.delete())
		{
			//prints the possible reason
			if (dir.list().length != 0)
			{
				Logger.error("FileStringUtility.deleteDir() - cannot delete non-empty directory '" + dir.getAbsolutePath() + "'");
			}
			else
			{
				Logger.error("FileStringUtility.deleteDir() - directory '" + dir.getAbsolutePath() + "' could not be deleted.");
			}
			return false;
		}

		return true;
	}

	/**************************************************************************
	 * deleting a existing directory with its structure
	 *
	 * @param dirPath the directory which should be deleted
	 * @param force if true forces to delete the entry (ie. the dirPath) even if
	 * it is a file
	 * @param recursive if true deletes the complete directory structure
	 **************************************************************************/
	static public boolean deleteDir(String dirPath, boolean force, boolean recursive)
	{
		File dir = new File(dirPath);
		File files[];

		if (!dir.exists())
		{
			Logger.error("FileStringUtility.deleteDir() - directory '" + dir.getAbsolutePath() + "' does not exist.");
			return false;
		}

		if (dir.isFile())
		{

			if (force)
			{ //delete the entry even if it is a file
				dir.delete();
				return true;
			}
			else
			{
				Logger.error("FileStringUtility.deleteDir() - '" + dir.getAbsolutePath() + "' was a file.");
				return false;
			}
		}

		if (recursive)
		{
			files = dir.listFiles();

			for (File file : files)
				deleteDir(file.getAbsolutePath(), true, true);
		}

		return deleteDir(dirPath);
	}

	/**************************************************************************
	 * List all file names in the directory recursively, relative to the
	 * starting directory.
	 *
	 * @param dirPath starting directory
	 * @param recursive goes into the subdirectories
	 **************************************************************************/
	static public ArrayList<String> listDir(String dirPath, boolean withDirs, boolean recursive)
	{
		ArrayList<String> fileNames = new ArrayList<String>();
		File dir = new File(dirPath);
		File files[];
		String fileName;

		if (!checkDir(dirPath))
		{
			Logger.msg(8, "FileStringUtility.listDir() - directory '" + dir.getAbsolutePath() + "' does not exist.");
			return null;
		}

		files = dir.listFiles();

		for (File file : files) {
			fileName = file.getName();

			if (file.isFile())
			{
				fileNames.add(dirPath + "/" + fileName);
			}
			else
			{
				if (recursive)
					fileNames.addAll(listDir(dirPath + "/" + fileName, withDirs, recursive));

				if (withDirs)
					fileNames.add(dirPath + "/" + fileName);
			}
		}

		return fileNames;
	}

	/**************************************************************************
	 * Open a URL or File as an InputStream
	 **************************************************************************/
	static public InputStream openTextStream(String source)
	{
		java.io.InputStream in = null;
		java.net.URL url = null;

		// Try to open URL connection first
		try
		{
			try
			{
				url = new URL(source);
				in = url.openStream();
			}
			catch (MalformedURLException e)
			{
				// Try to open plain file, if `configFile' is not a
				// URL specification
				in = new FileInputStream(source);
			}
		}
		catch (java.io.IOException ex)
		{
			Logger.error("FileStringUtility.openTextStream() - could not load text stream:" + source);
		}
		return in;
	}

	/**************************************************************************
	 * Load the contents of the configuration file
	 **************************************************************************/
	static public java.util.Properties loadConfigFile(String configFile)
	{
		java.io.BufferedInputStream bin = null;
		java.io.InputStream in = openTextStream(configFile);
		java.util.Properties props = new java.util.Properties();

		if (in != null)
		{
			try
			{
				bin = new java.io.BufferedInputStream(in);
				props.load(bin);
				in.close();
			}
			catch (IOException ex)
			{
				Logger.error("FileStringUtility.loadConfigFile() - could not load configuration file '" + configFile+"'");
			}
		}
		return props;
	}

	/**************************************************************************
	 * Load the contents of the language file
	 * *************************************************************************/
	static public Hashtable<String, String> loadLanguageFile(String configFile)
	{
		try
		{
			String language = FileStringUtility.file2String(configFile);
			Hashtable<String, String> props = new Hashtable<String, String>();
			StringTokenizer tok = new StringTokenizer(language, "\n");
			while (tok.hasMoreTokens())
			{
				String t = tok.nextToken();
				int sep = t.indexOf("=");
				if (sep >0)props.put(t.substring(0,sep),t.substring(sep+1));
			}
			return props;
		}
		catch (Exception e)
		{
			Logger.error("FileStringUtility.loadLanguageFile() - could not load language file '" + configFile+"'");
			Logger.error(e);
			return new Hashtable<String, String>();
		}

	}

	/**************************************************************************
	 * Load the contents of the configuration file
	 **************************************************************************/
	static public void appendConfigFile(java.util.Properties props, String configFile)
	{
		java.io.BufferedInputStream bin = null;
		java.io.InputStream in = openTextStream(configFile);

		if (in != null)
		{
			try
			{
				bin = new java.io.BufferedInputStream(in);
				props.load(bin);
				in.close();
			}
			catch (java.io.IOException ex)
			{
    			Logger.error("FileStringUtility.appendConfigFile() - could not append configuration file '" + configFile+"'");
			}
		}
	}
    public static String convert(String init)
    {
        if (init==null) return null;
        return init
            .replace('\'', '_')
            .replace('\\', '_')
            .replace('/', '_')
            .replace('\"', '_')
            .replace(':', '_')
            .replace('*', '_')
            .replace('?', '_')
            .replace('<', '_')
            .replace('>', '_')
            .replace('|', '_')
            .replace('(', '[')
            .replace(')', ']')
            .replace(',','_');    }
    public static String replaceall(String src,String from,String to)
    {
        StringBuffer tmp=new StringBuffer(src);
        int length = from.length();
        int index = tmp.toString().indexOf(from);
        while (index>0)
        {
            tmp.replace(index,index+length,to);
            index = tmp.toString().indexOf(from);
        }
        return tmp.toString();
    }
    public static String toAlphaNum(String source)
    {
        byte[] sourceb = source.getBytes();
        for (int i=0;i<sourceb.length;i++)
        {
            if (sourceb[i]<'0'||(sourceb[i]>'9'&&sourceb[i]<'A')||(sourceb[i]>'Z'&&sourceb[i]<'_')||sourceb[i]>'z')
                sourceb[i]='_';
        }
        return new String(sourceb);

    }

}