java/ch/wlkl/javaExamples/FileUt.java

/*
 * FileUt.java
 *
 * Created on 25. Dezember 2004, 10:58
 */

package ch.wlkl.javaExamples;

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.FileWriter;
import java.util.Date;

/**
 * 
 * @author walter
 */
public class FileUt {

    /** Creates a new instance of FileUt */

    public FileUt(File fi) {
        list = new File[1];
        list[0] = fi;
    }

    private FileUt(File fi, FileUt pa) {
        list = fi.listFiles();
        parent = pa;
    }

    boolean doFile = true;

    final File[] list;

    FileUt sub = null;

    FileUt parent = null;

    int ix = -1;

    public String relative(String path) {
        if (path.startsWith(list[ix].getPath()))
            return path.substring(1 + list[ix].getPath().length());
        else
            return path;
    }

    public File nextFlat() {
        File fi;
        if (list == null)
            return null;
        if (doFile) {
            for (ix = ix + 1; ix < list.length; ix++) {
                if (list[ix].isFile())
                    return list[ix];
            }
            doFile = false;
            ix = -1;
        }
        for (ix = ix + 1; ix < list.length; ix++) {
            if (list[ix].isDirectory())
                return list[ix];
        }
        return null;
    }

    public File nextOne() {
        File fi;
        while (true) {
            if (sub == null)
                ;
            else if (null == (fi = sub.nextFlat()))
                sub = null;
            else
                return fi;
            if (null == (fi = nextFlat()))
                return null;
            if (fi.isFile())
                return fi;
            else
                sub = new FileUt(list[ix], this);
        }
    }

    public File next() {
        File fi;
        while (true) {
            if (sub == null) {
                fi = nextFlat();
                if (fi == null)
                    return null;
            } else {
                fi = sub.nextFlat();
            }
            if (fi == null)
                sub = sub.parent;
            else if (fi.isFile())
                return fi;
            else
                sub = new FileUt(fi, sub);
        }
    }

    public static void copy(File fi, BufferedWriter wri) {
        BufferedReader in;
        int chars = 0;
        String s;
        try {
            in = new BufferedReader(new FileReader(fi));
            for (int i = 1; (s = in.readLine()) != null; i++) {
                chars += s.length();
                if (wri == null) {
                    say(i + " len " + s.length() + " " + chars + ": " + s);
                } else {
                    wri.write(s, 0, s.length());
                    wri.newLine();
                }
            }
        } catch (Exception ex) {
            say("caught exception " + ex);
        }
    }

    public static void say(String a) {
        System.out.println(a);
    }

    public static void say(File fi) {
        say(fi + " dir " + fi.isDirectory());
        say("absoluteFile  " + fi.getAbsoluteFile() + ": "
                + fi.getAbsoluteFile().getClass());
        say("absolutePath  " + fi.getAbsolutePath() + ": "
                + fi.getAbsolutePath().getClass());
        say("parent        " + fi.getParent());
        try {
            say("canonicalFile " + fi.getCanonicalFile());
        } catch (Exception ex) {
            say("canonicalFile Exception " + ex);
        }
        try {
            say("canonicalPath " + fi.getCanonicalFile());
        } catch (Exception ex) {
            say("canonicalPath Exception " + ex);
        }
    }

    public static void test(String s) {
        File fi = new File("D:\\infProj\\zkb");
        FileUt ut = new FileUt(fi);
        DirOut dest = new DirOut("d:\\test\\fileUt");
        Writer wri = null;
        say("start test " + s);
        if (s == "file") {
            say(fi);
            say(new File("tst.txt"));
        } else if (s == "next") {
            while ((fi = ut.next()) != null)
                say(fi.getAbsolutePath() + " isFile " + fi.isFile() + " len "
                        + fi.length() + " lastMod "
                        + new Date(fi.lastModified()));

        } else if (s == "nextFlat") {
            while ((fi = ut.nextFlat()) != null)
                say(fi.getAbsolutePath() + " isFile " + fi.isFile() + " len "
                        + fi.length() + " lastMod "
                        + new Date(fi.lastModified()));
        } else {
            say("bad test " + s);
        }
        say("end test " + s);
    }

    /**
     * @param rec: the object to report
     * @param t:   the text to report
     */
    public static void fail(Object rec, String t) {
        System.out.println("fatal fail: " + t);
        System.out.println("fatal fail: receiver " + rec.toString());
        throw new AssertionError(t);
    }

    public static void fail(String t) {
        System.out.println("fatal fail: " + t);
        throw new AssertionError(t);
    }

    public static void cp(String[] args) {
        File src;
        File dest;
        char destType;
        Out out = null;
        say("args " + args.length);
        TarScanner sc = new TarScanner(args);
        dest = new File(sc.last());
        destType = sc.type;
        say("last " + dest + ' ' + destType + " count " + sc.count);
        if (sc.count < 2)
            fail("need two or more paths");
        sc.reset();
        src = new File(sc.next());
        if (destType == 'f') {
            if (dest.isFile()) {
                if (sc.count > 2 || sc.type != 'f' || !src.isFile())
                    fail("cp to file only from file");
                try {
                    copy(src, new BufferedWriter(new FileWriter(dest)));
                } catch (Exception ex) {
                    fail("copy " + src + " to " + dest + " caught " + ex);
                }
                return;
            }
            out = new DirOut(dest.getPath());
        }

        for (int i = 1; i < sc.count; i++)
            say("from  " + sc.next() + ' ' + sc.type);
        say("last " + sc.next() + ' ' + sc.type);
    }

    public static void main(String[] args) {
        say("args " + args.length);
        TarScanner sc = new TarScanner(args);
        say("last " + sc.last() + ' ' + sc.type + " count " + sc.count);
        sc.reset();
        for (int i = 1; i < sc.count; i++)
            say("from  " + sc.next() + ' ' + sc.type);
        say("last " + sc.next() + ' ' + sc.type);
        for (int i = 0; i < args.length; i++)
            say("arg " + i + ": " + args[i]);
        File fi = new File("D:\\infProj\\zkb");
        if (fi != null)
            return;
        FileUt src = new FileUt(fi);
        DirOut dest = new DirOut("d:\\temp\\fileUt");
        BufferedWriter wri = null;
        test("file");
        // test("next");
        // test("nextFlat");
        while ((fi = src.next()) != null) {
            say(fi.getAbsolutePath() + " isFile " + fi.isFile() + " len "
                    + fi.length() + " lastMod " + new Date(fi.lastModified()));
            if (fi.isFile()) {
                say("relative " + src.relative(fi.getPath()));
                wri = dest.begin(src.relative(fi.getPath()));
                src.copy(fi, wri);
                dest.end(src.relative(fi.getPath()));
            }

        }
        say("end");
    }
}

abstract class Out {
    String name = null;

    public void close() {
        if (name != null)
            fail("close with self.name=" + name);
    };

    public BufferedWriter begin(String aName) {
        if (name != null)
            fail("begin(" + aName + ") but null != this.name=" + name);
        name = aName;
        return null;
    }

    public void end(String aName) {
        if (!name.equals(aName))
            fail("end(" + aName + ") != this.name=" + name);
        name = null;
    }

    public void fail(String t) {
        FileUt.fail(this, t);
    }

}

class DirOut extends Out {
    File dir = null;

    BufferedWriter wri;

    public DirOut(String path) {
        dir = new File(path);
        if (dir.exists() && !dir.isDirectory())
            fail("not a directory: " + path);
    }

    public BufferedWriter begin(String aName) {
        File fi;
        super.begin(aName);
        fi = new File(dir, aName);
        System.out.println(fi + " is write " + fi.canWrite());
        try {
            wri = new BufferedWriter(new FileWriter(fi));
        } catch (Exception ex) {
            System.out.println("creating " + aName + " in " + dir
                    + " caught exception " + ex);
            try {
                fi.getParentFile().mkdirs();
                wri = new BufferedWriter(new FileWriter(fi));
            } catch (Exception e2) {
                fail("creating " + aName + " in " + dir + " caught exception "
                        + e2);
            }
        }
        return wri;
    }

    public void end(String aName) {
        super.end(aName);
        try {
            wri.close();
        } catch (Exception ex) {
            fail("close caught " + ex);
        }
    }
}

class TarScanner {
    String[] args;

    public int ix;

    public int count = -1;

    public char type;

    public TarScanner(String[] args) {
        this.args = args;
        reset();
    }

    public void reset() {
        ix = -1;
        type = 'f';
    }

    public String next() {
        for (ix++; ix < args.length; ix++) {
            if (args[ix].length() < 1)
                ;
            else if (args[ix].charAt(0) != '-')
                return args[ix];
            else if (args[ix].length() < 2)
                fail("bad option " + args[ix]);
            else if (!args[ix].equals("--")) {
                if (args[ix].charAt(1) == 'f' || args[ix].charAt(1) == 't')
                    type = args[ix].charAt(1);
                else
                    fail("bad option " + args[ix]);
                if (args[ix].length() > 2)
                    return args[ix].substring(2);
            }
        }
        return null;
    }

    public String last() {
        String cur;
        String prev = null;
        count = 0;
        while (null != (cur = next())) {
            count++;
            prev = cur;
        }
        return prev;
    }

    void fail(String t) {
        FileUt.fail(this, t);
    }
}