This commit is contained in:
Ziver Koc 2010-10-27 18:02:44 +00:00
parent 51e9da7c9b
commit ca8f6278b1
30 changed files with 88 additions and 79 deletions

View file

@ -0,0 +1,347 @@
package zutil.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import zutil.Dumpable;
/**
* @author Ziver
* this class can print strings to multiple PrintStreams
*/
public class MultiPrintStream extends PrintStream {
//the print streams that will print
private ArrayList<PrintStream> streams;
//a instance of this class
public static MultiPrintStream out = new MultiPrintStream();
public MultiPrintStream(){
super(new PrintStream(System.out));
streams = new ArrayList<PrintStream>();
streams.add(new PrintStream(System.out));
}
/**
* This constructor makes a simple PrintStream that prints to the console and to a file
* @param file is the file name to output to
*/
public MultiPrintStream(String file){
super(new PrintStream(System.out));
try {
streams = new ArrayList<PrintStream>();
streams.add(new PrintStream(System.out));
streams.add(new PrintStream(new File(file)));
} catch (FileNotFoundException e) {
System.out.println("Error when declaring PrintStream!!");
e.printStackTrace();
}
}
/**
* This constructor takes a array of PrintStreams to be used
* @param streams is a array of the streams that will be used
*/
public MultiPrintStream(PrintStream[] streams){
super(streams[0]);
this.streams = new ArrayList<PrintStream>();
for(int i=0; i<streams.length ;i++){
this.streams.add(streams[i]);
}
}
/**
* This constructor takes a array of PrintStreams to be used
* @param streams is a array of the streams that will be used
*/
public static void makeInstance(MultiPrintStream instanceStream){
out = instanceStream;
}
/**
* Adds a PrintStream to the list of streams
* @param p is the PrintStream to add
*/
public void addPrintStream(PrintStream p){
streams.add(p);
}
/**
* Remove a PrintStream from the list
* @param p is the PrintStream to remove
*/
public void removePrintStream(PrintStream p){
streams.remove(p);
}
/**
* Remove a PrintStream from the list
* @param p is the index of the PrintStream to remove
*/
public void removePrintStream(int p){
streams.remove(p);
}
/**
* writes to all the PrintStreams
*/
public void write(int b) {
for(int i=0; i<streams.size() ;i++)
streams.get(i).write(b);
}
/**
* writes to all the PrintStreams
*/
public void write(byte buf[], int off, int len){
for(int i=0; i<streams.size() ;i++)
streams.get(i).write(buf, off, len);
}
/**
* Prints with a new line to all the PrintStreams
*/
public void println(String s){
for(int i=0; i<streams.size() ;i++)
streams.get(i).println(s);
}
/**
* Prints to all the PrintStreams
*/
public void print(String s){
for(int i=0; i<streams.size() ;i++)
streams.get(i).print(s);
}
public void println(){ println("");}
public void println(boolean x){ println(String.valueOf(x));}
public void println(char x){ println(String.valueOf(x));}
public void println(char[] x){ println(new String(x));}
public void println(double x){ println(String.valueOf(x));}
public void println(float x){ println(String.valueOf(x));}
public void println(int x){ println(String.valueOf(x));}
public void println(long x){ println(String.valueOf(x));}
public void println(Object x){ println(String.valueOf(x));}
public void print(boolean x){ print(String.valueOf(x));}
public void print(char x){ print(String.valueOf(x));}
public void print(char[] x){ print(new String(x));}
public void print(double x){ print(String.valueOf(x));}
public void print(float x){ print(String.valueOf(x));}
public void print(int x){ print(String.valueOf(x));}
public void print(long x){ print(String.valueOf(x));}
public void print(Object x){ print(String.valueOf(x));}
public boolean checkError(){
for(int i=0; i<streams.size() ;i++)
if(streams.get(i).checkError())
return true;
return false;
}
/**
* closes all the PrintStreams
*/
public void close(){
for(int i=0; i<streams.size() ;i++)
streams.get(i).close();
}
/**
* Dumps the content of:
* <br>- Array content
* <br>- Map content (HashMap etc.)
* <br>- List content (ArrayList, LinkedList etc.)
* <br>- InputStream content (Prints out until the end of the stream)
* <br>- Reader content (Prints out until the end of the reader)
* <br>- Instance variables of a Object
*
* @param o is the Object to dump
*/
public void dump( Object o ){
println(dumpToString( o ));
}
/**
* Dumps the content of:
* <br>- Array content
* <br>- Map content (HashMap etc.)
* <br>- List content (ArrayList, LinkedList etc.)
* <br>- InputStream content (Prints out until the end of the stream)
* <br>- Reader content (Prints out until the end of the reader)
* <br>- Instance variables of a Object
*
* @param o is the Object to dump
* @return A String with all the printed data
*/
public String dumpToString( Object o) {
return dumpToString(o, "");
}
/**
* Dumps the content of:
* <br>- Array content
* <br>- Map content (HashMap etc.)
* <br>- List content (ArrayList, LinkedList etc.)
* <br>- InputStream content (Prints out until the end of the stream)
* <br>- Reader content (Prints out until the end of the reader)
* <br>- Instance variables of a Object
*
* @param o is the Object to dump
* @param head is the string that will be put in front of every line
* @return A String with all the printed data
*/
private String dumpToString( Object o , String head) {
if(o == null)
return "NULL";
StringBuffer buffer = new StringBuffer();
Class<?> oClass = o.getClass();
buffer.append( oClass.getName() );
String nextHead = head + "\t";
// Prints out Arrays
if ( oClass.isArray() ) {
buffer.append( "[" );
for ( int i=0; i<Array.getLength(o) ;i++ ) {
Object value = Array.get(o,i);
buffer.append("\n");
buffer.append(nextHead);
buffer.append( (dumbCapable(value) ? dumpToString(value, nextHead) : value) );
if ( i+1<Array.getLength(o) )
buffer.append( "," );
}
buffer.append( "\n" );
buffer.append(head);
buffer.append( "]" );
}
// Prints out a list
else if(o instanceof Collection){
Iterator<?> it = ((Collection<?>)o).iterator();
buffer.append( "{" );
while(it.hasNext()){
Object value = it.next();
buffer.append("\n");
buffer.append(nextHead);
buffer.append( (dumbCapable(value) ? dumpToString(value, nextHead) : value) );
if(it.hasNext())
buffer.append( "," );
}
buffer.append( "\n" );
buffer.append(head);
buffer.append( "}" );
}
// Prints out a Map
else if(o instanceof Map){
Iterator<?> it = ((Map<?,?>)o).keySet().iterator();
buffer.append( "{" );
while(it.hasNext()){
Object key = it.next();
Object value = ((Map<?,?>)o).get(key);
buffer.append("\n");
buffer.append(nextHead);
buffer.append( key );
buffer.append( "=>" );
buffer.append( (dumbCapable(value) ? dumpToString(value, nextHead) : value) );
if(it.hasNext())
buffer.append( "," );
}
buffer.append( "\n" );
buffer.append(head);
buffer.append( "}" );
}
// Prints out data from InputStream
else if(o instanceof InputStream){
buffer.append( " =>{\n" );
try {
InputStream in = (InputStream)o;
int tmp;
while((tmp = in.read()) != -1){
buffer.append(nextHead);
buffer.append( (char)tmp );
}
in.close();
} catch (IOException e) {
e.printStackTrace(this);
}
buffer.append( "\n" );
buffer.append(head);
buffer.append( "}" );
}
// Prints out data from InputStream
else if(o instanceof Reader){
buffer.append( " =>{\n" );
try {
Reader in = (Reader)o;
int tmp;
while((tmp = in.read()) != -1){
buffer.append(nextHead);
buffer.append( (char)tmp );
}
in.close();
} catch (IOException e) {
e.printStackTrace(this);
}
buffer.append( "\n" );
buffer.append(head);
buffer.append( "}" );
}
// Prints out Object properties
else{
buffer.append( "{" );
while ( oClass != null ) {
Field[] fields = oClass.getDeclaredFields();
for ( int i=0; i<fields.length; i++ ) {
fields[i].setAccessible( true );
buffer.append("\n");
buffer.append(nextHead);
buffer.append( fields[i].getType().getSimpleName() );
buffer.append( " " );
buffer.append( fields[i].getName() );
buffer.append( " = " );
try {
Object value = fields[i].get(o);
if (value != null) {
buffer.append( (dumbCapable(value) ? dumpToString(value, nextHead) : value) );
}
} catch ( IllegalAccessException e ) {}
if ( i+1<fields.length )
buffer.append( "," );
}
oClass = oClass.getSuperclass();
}
buffer.append( "\n" );
buffer.append(head);
buffer.append( "}" );
}
return buffer.toString();
}
/**
* An helper function for the dump function.
*/
private boolean dumbCapable(Object o){
if(o != null){
if(o.getClass().isArray()) return true;
else if(o instanceof Collection)return true;
else if(o instanceof Map)return true;
else if(o instanceof InputStream)return true;
else if(o instanceof Reader)return true;
else if(o instanceof Dumpable)return true;
}
return false;
}
}

View file

@ -0,0 +1,18 @@
package zutil.io.file;
import java.io.File;
/**
* Interface for the FileWatcher class
*
* @author Ziver
*/
public interface FileChangeListener{
/**
* This method is called when there is a change in a file
*
* @param file The file that has changed
*/
public void fileChangedEvent(File file);
}

View file

@ -0,0 +1,290 @@
package zutil.io.file;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import zutil.io.MultiPrintStream;
/**
* File path utilities
*
* @author Ziver
*/
public class FileUtil {
/**
* Returns a String with a relative path from the given path
*
* @param file is the file to get a relative path from
* @param path is the path
* @return A String with a relative path
*/
public static String relativePath(File file, String path){
String absolute = file.getAbsolutePath();
String tmpPath = path.replaceAll(
"[/\\\\]",
Matcher.quoteReplacement(File.separator));
String relative = absolute.substring(
absolute.indexOf(tmpPath)+path.length(),
absolute.length());
return relative;
}
/**
* Returns the File object for the given file.
* Can not point to files in JAR files.
*
* @param path is the path to the file (no / if not absolute path)
* @return A File object for the file
*/
public static File find(String path){
try {
File file = new File(path);
if(file!=null && file.exists()){
return file;
}
return new File(findURL(path).toURI());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returns the URL to the given file
*
* @param path is the path to the file (no / if not absolute path)
* @return A URL object for the file
* @throws URISyntaxException
*/
public static URL findURL(String path){
return Thread.currentThread().getContextClassLoader().getResource(path);
}
/**
* Returns a InputStream from the path
*
* @param path is the path to the file (no / if not absolute path)
* @return A InputStream object for the file
*/
public static InputStream getInputStream(String path){
try {
File file = new File(path);
if(file!=null && file.exists()){
return new BufferedInputStream( new FileInputStream( file ) );
}
return Thread.currentThread().getContextClassLoader()
.getResourceAsStream(path);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Reads and returns the content of a file as a String.
* Or use FileUtils.readFileToString(file);
*
* @param file is the file to read
* @return The file content
* @throws IOException
*/
public static String getFileContent(File file) throws IOException{
return getContent( new FileInputStream(file) );
}
/**
* Reads and returns the content of a file as a String.
* Or use FileUtils.readFileToString(file);
*
* @param url is the url to read
* @return The file content
* @throws IOException
*/
public static String getContent(URL url) throws IOException{
return getContent( url.openStream() );
}
/**
* Reads and returns the content of a file as a String.
* Or use FileUtils.readFileToString(file);
*
* @param stream is the file stream to read
* @return The file content
* @throws IOException
*/
public static String getContent(InputStream stream) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
StringBuffer ret = new StringBuffer();
int tmp;
while((tmp=in.read()) != -1){
ret.append((char)tmp);
}
in.close();
return ret.toString();
}
/**
* Cache for the search functions
*/
private static HashMap<SearchItem,List<File>> search_cache = new HashMap<SearchItem,List<File>>();
/**
* An Cache Item class to identify different cached items
* @author Ziver
*/
private static class SearchItem{
private File dir;
private boolean folders;
private int recurse;
protected SearchItem(File dir, boolean folders, int recurse){
this.dir = dir;
this.folders = folders;
this.recurse = recurse;
}
public boolean equals(Object o){
if(o!=null && o instanceof SearchItem){
SearchItem si = (SearchItem)o;
return dir.equals(si.dir) && folders == si.folders && recurse == si.recurse;
}
return false;
}
public int hashCode(){
int hash = 133;
hash = 23 * hash + dir.hashCode();
hash = 23 * hash + (folders ? 1 : 0);
hash = 23 * hash + recurse;
return 0;
}
}
/**
* Same as search(File dir) but it caches the result
* to be used next time this function is called with
* the same parameters.
*/
public static List<File> cachedSearch(File dir){
return cachedSearch(dir, new LinkedList<File>(), true);
}
/**
* Same as search(File dir, List<File> fileList, boolean recursive)
* but is caches the result to be used next time this function is
* called with the same parameters.
*/
public static List<File> cachedSearch(File dir, List<File> fileList, boolean recursive){
return cachedSearch(dir, new LinkedList<File>(), false, (recursive ? Integer.MAX_VALUE : 0));
}
/**
* Same as search(File dir, List<File> fileList, boolean folders, int recurse)
* but is caches the result to be used next time this function is called
* with the same parameters.
*/
public static List<File> cachedSearch(File dir, List<File> fileList, boolean folders, int recurse){
SearchItem si = new SearchItem(dir, folders, recurse);
if( search_cache.containsKey(si) ){
fileList.addAll( search_cache.get(si) );
return fileList;
}
search(dir, fileList, folders, recurse);
search_cache.put(si, fileList);
return fileList;
}
/**
* Returns a List with all the files in a folder and sub folders
*
* @param dir is the directory to search in
* @return The List with the files
*/
public static List<File> search(File dir){
return search(dir, new LinkedList<File>(), true);
}
/**
* Returns a ArrayList with all the files in a folder and sub folders
*
* @param dir is the directory to search in
* @param fileList is the List to add the files to
* @param recursive is if the method should search the sub directories to.
* @return A List with the files
*/
public static List<File> search(File dir, List<File> fileList, boolean recursive){
return search(dir, new LinkedList<File>(), false, (recursive ? Integer.MAX_VALUE : 0));
}
/**
* Returns a ArrayList with all the files in a folder and sub folders
*
* @param dir is the directory to search in
* @param fileList is the List to add the files to
* @param folders is if the method should add the folders to the List
* @param recurse is how many times it should recurse into folders
* @return A List with the files and/or folders
*/
public static List<File> search(File dir, List<File> fileList, boolean folders, int recurse){
if(recurse<0)
return fileList;
--recurse;
if(folders){
MultiPrintStream.out.println("Dir Found : "+dir);
fileList.add( dir );
}
File file;
String[] temp = dir.list();
if(temp != null){
for(int i=0; i<temp.length ;i++){
file = new File(dir.getPath()+File.separator+temp[i]);
if(file.isDirectory()){
search(new File(dir.getPath()+File.separator+temp[i]+File.separator), fileList, folders, recurse);
}
else if(file.isFile()){
MultiPrintStream.out.println("File Found: "+file);
fileList.add(file);
}
}
}
return fileList;
}
/**
* Returns the extension of the file
*
* @param file is the file
* @return The extension
*/
public static String fileExtension(File file){
return fileExtension(file.getName());
}
/**
* Returns the extension of the file
*
* @param file is the file
* @return The extension
*/
public static String fileExtension(String file){
if(file.lastIndexOf(".")==-1)
return "";
return file.substring(file.lastIndexOf(".")+1,file.length());
}
}

View file

@ -0,0 +1,67 @@
package zutil.io.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Timer;
import java.util.TimerTask;
import zutil.io.MultiPrintStream;
/**
* This class calls a given listener
* when a file is changed
*
* @author Ziver
*
*/
public class FileWatcher extends TimerTask{
private FileChangeListener listener;
private long lastChanged;
private File file;
/**
* Creates a watcher for the given file whit the check
* interval of 1 second
*
* @param file is the file to check
* @throws FileNotFoundException
*/
public FileWatcher(File file) throws FileNotFoundException{
this(file, 1000);
}
/**
* Creates a watcher for the given file whit the given
* check interval
*
* @param file is the file
* @param intervall is the interval
* @throws FileNotFoundException
*/
public FileWatcher(File file, int intervall) throws FileNotFoundException{
if(file==null || !file.exists())
throw new FileNotFoundException("File not found: "+file);
this.file = file;
lastChanged = file.lastModified();
Timer t = new Timer(true);
t.schedule(this, 0, intervall);
}
public void setListener(FileChangeListener listener){
this.listener = listener;
}
@Override
public void run() {
if (lastChanged != file.lastModified()) {
lastChanged = file.lastModified();
if(listener != null){
listener.fileChangedEvent(file);
}
else{
MultiPrintStream.out.println("File Changed: "+file);
}
}
}
}