Java Code Examples for de.waldheinz.fs.FsDirectory

Following code examples demonstrate how to use de.waldheinz.fs.FsDirectoryfrom android. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use de.waldheinz.fs.FsDirectoryand various code implementation of this class.

    public FsDirectory getParent() {
        checkValid();
        
        return parent;
    } 


	public FsDirectory getParent() {
		checkValid();

		return parent;
	} 

    protected static List<FileInfo> readDirRecur(String parent, FsDirectory dir) throws IOException {
    	List <FileInfo>files = new ArrayList<FileInfo>();
        Iterator<FsDirectoryEntry> itr = dir.iterator();
    	while(itr.hasNext()) {
    		FsDirectoryEntry entry = itr.next();
    		if (entry.isDirectory()) {
    			if (entry.getName().equals(".") || entry.getName().equals(".."))
    				continue;
    			System.out.format("DIR: %s\n", entry.getName());
    			files.addAll(readDirRecur(parent + entry.getName() + "/", entry.getDirectory()));
    		} else {
    			files.add(new FileInfo(parent + entry.getName(), (int)entry.getFile().getLength()));
    			System.out.format("FILE: %s (%d)\n", entry.getName(), entry.getFile().getLength());
    		}
    	}
    	return files;
    } 

    public VirtualDisk loadImage(File imageFile) throws VirtualDiskException {
        FatFileSystem fs = null;
        FileDisk fileDisk = null;
        try {
            fileDisk = new FileDisk(imageFile, false);
            fs = FatFileSystem.read(fileDisk, true);
        } catch(IOException e) {
            throw new VirtualDiskException("Failed to read DOS image; reason: " + e.toString()
                    + ", image: " + imageFile.getAbsolutePath(), e);
        }

        DosVirtualDisk virtualDisk = new DosVirtualDisk(fs, imageFile.getName());
        try {
            FsDirectory rootDirectory = fs.getRoot();
            VirtualDirectory root = new VirtualDirectory("/");

            iterateReadDirectory(root, rootDirectory);

            virtualDisk.setRootContent(root);

        } catch(IOException e) {
            throw new VirtualDiskException("Failed to read DOS files from image; reason: " + e.toString(), e);
        }

        return virtualDisk;
    } 

    private void iterateReadDirectory(VirtualDirectory parent, FsDirectory directory) throws IOException {
        Iterator<FsDirectoryEntry> iterator = directory.iterator();
        while(iterator.hasNext()) {
            FsDirectoryEntry entry = iterator.next();
            if(entry.isFile()) {
                try {
                    VirtualFile virtualFile = new VirtualFile(parent, entry.getName());
                    FsFile fsFile = entry.getFile();
                    ByteBuffer bb = ByteBuffer.allocate((int) fsFile.getLength());
                    fsFile.read(0, bb);
                    virtualFile.setContent(bb);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            } else {
                VirtualDirectory newParent = new VirtualDirectory(parent, entry.getName());
                iterateReadDirectory(newParent, entry.getDirectory());
            }
        }
    } 

    public BackupTask(BackupTaskListener listener, FsDirectory srcDir, File destDir, List<String> extensions, boolean delete, boolean overwrite) {
        this.listener = listener;
        this.srcDir = srcDir;
        this.destDir = destDir;
        this.extensions = extensions;
        this.delete = delete;
        this.overwrite = overwrite;
    } 

    private FileSystem mountMockDevice() throws IOException {
        Log.d("MountTask", "creating fs hierarchy...");
        BlockDevice dev = new RamDisk(100 * 1024 * 1024);
        Log.d("MountTask", "BlockDevice created...");
        FileSystem fs = SuperFloppyFormatter.get(dev).format();
        Log.d("MountTask", "File system formatted...");
        FsDirectory rootDir = fs.getRoot();
        for (int i = 0; i < 10; i++) {
            addMockFile(rootDir, i, 1024 * 5);
        }
        FsDirectoryEntry dcim = rootDir.addDirectory("DCIM");
        FsDirectoryEntry subDir = dcim.getDirectory().addDirectory("100_PANO");
        for (int i = 0; i < 155; i++) {
            addMockFile(subDir.getDirectory(), i, 1024 * 100);
        }
        return fs;
    } 

    private void addMockFile(FsDirectory directory, int id, int preferredSize) throws IOException {
        FsFile fsFile = directory.addFile(String.format("image_%02d.jpg", id)).getFile();
        String content = String.format(Locale.getDefault(), "%1d", id % 10);
        byte[] buffer = new byte[preferredSize];
        Arrays.fill(buffer, (byte) content.charAt(0));
        ByteBuffer buff = ByteBuffer.wrap(buffer);
        buff.rewind();
        fsFile.write(0, buff);
        fsFile.flush();
    } 

    public VirtualDisk loadImage(File imageFile) throws VirtualDiskException {

        FatFileSystem fs = null;
        try {
            MsaDisk msaDisk = new MsaDisk(imageFile);

            msaDisk.load();

            fs = FatFileSystem.read(msaDisk, true);
        } catch(IOException e) {
            throw new VirtualDiskException("Failed to read MSA files from image; reason: " + e.toString(), e);
        }

        StVirtualDisk virtualDisk = new StVirtualDisk(ImageType.atarist_MSA, imageFile.getName());
        try {
            FsDirectory rootDirectory = fs.getRoot();
            VirtualDirectory root = new VirtualDirectory("/");

            System.out.println("read root...");
            iterateReadDirectory(0, root, rootDirectory);
            System.out.println("contents read.");

            virtualDisk.setRootContent(root);
        } catch(IOException e) {
            throw new VirtualDiskException("Failed to read ST files from image; reason: " + e.toString(), e);
        }

        return virtualDisk;
    } 

    private void iterateReadDirectory(int indent, VirtualDirectory parent, FsDirectory directory) throws IOException {
        Iterator<FsDirectoryEntry> iterator = directory.iterator();
        while(iterator.hasNext()) {
            FsDirectoryEntry entry = iterator.next();
            if(entry.isFile()) {
                try {
                    VirtualFile virtualFile = new VirtualFile(parent, entry.getName());
                    FsFile fsFile = entry.getFile();
                    ByteBuffer bb = ByteBuffer.allocate((int) fsFile.getLength());
                    fsFile.read(0, bb);
                    virtualFile.setContent(bb);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            } else {
                if(!entry.getName().equals(".") && !entry.getName().equals("..")) {
                    VirtualDirectory newParent = new VirtualDirectory(parent, entry.getName());
                    iterateReadDirectory(indent + 4, newParent, entry.getDirectory());
                }
            }
        }
    } 

    private void listDirectories(FsDirectory dir, String ident) throws IOException {

        final Iterator<FsDirectoryEntry> i = dir.iterator();
        
        while (i.hasNext()) {
            final FsDirectoryEntry e = i.next();
            
            if (e.isDirectory()) {
                System.out.println(ident + "- " + e.getName());

                if (e.getName().equals(".") || e.getName().equals(".."))
                    continue;
                
                listDirectories(e.getDirectory(), ident + "   ");
            } else {
                checkFile(e, ident);
            }
        }
    } 

    protected void walkFileTree(FsDirectory srcDir, File destDir) throws IOException {
        if (srcDir == null) {
            throw new IllegalArgumentException("srcDir can't be null");
        }
        if (destDir == null) {
            throw new IllegalArgumentException("destDir can't be null");
        }
        Iterator<FsDirectoryEntry> i = srcDir.iterator();
        while (i.hasNext()) {
            FsDirectoryEntry entry = i.next();
            if (entry.isFile()) {
                visitFile(entry, destDir);
            } else if (entry.isDirectory() && !".".equals(entry.getName()) && !"..".equals(entry.getName())) {
                File newSubDir = new File(destDir, entry.getName());
                preVisitDirectory(entry, newSubDir);
                walkFileTree(entry.getDirectory(), newSubDir);
                postVisitDirectory(entry, newSubDir);
            }
        }
    } 

    public FsDirectory getParent() {
        checkValid();
        
        return parent;
    } 

    public void handle(IdentificationRequest request) throws IOException {
        BlockDevice device    = new FatReader(request.getWindowReader());
        FileSystem fatSystem = FatFileSystem.read(device, OPEN_READ_ONLY);
        FsDirectory root      = fatSystem.getRoot();
        FatArchiveWalker walker    = new FatArchiveWalker(droid, resultHandler, request.getIdentifier());
        walker.walk(root);
    } 

    public VirtualDisk loadImage(File imageFile) throws VirtualDiskException {
        String diskName = imageFile.getName();

        FileDisk fileDisk = null;
        FatFileSystem fs = null;
        try {
            fileDisk = new FileDisk(imageFile, false);
            fs = FatFileSystem.read(fileDisk, true);
        } catch(IOException e) {
            throw new VirtualDiskException("Failed to read ST image; reason: " + e.toString()
                    + ", image: " + imageFile.getAbsolutePath(), e);
        }

        StVirtualDisk virtualDisk = new StVirtualDisk(imageFile.getName());
        try {
            FsDirectory rootDirectory = fs.getRoot();
            VirtualDirectory root = new VirtualDirectory("/");

            System.out.println("read root...");
            iterateReadDirectory(0, root, rootDirectory);
            System.out.println("contents read.");

            virtualDisk.setRootContent(root);
        } catch(IOException e) {
            throw new VirtualDiskException("Failed to read ST files from image; reason: " + e.toString(), e);
        }

        return virtualDisk;
    } 

    private void iterateReadDirectory(int indent, VirtualDirectory parent, FsDirectory directory) throws IOException {
        Iterator<FsDirectoryEntry> iterator = directory.iterator();
        while(iterator.hasNext()) {
            FsDirectoryEntry entry = iterator.next();
            if(entry.isFile()) {
                try {
                    VirtualFile virtualFile = new VirtualFile(parent, entry.getName());
                    FsFile fsFile = entry.getFile();
                    ByteBuffer bb = ByteBuffer.allocate((int) fsFile.getLength());
                    fsFile.read(0, bb);
                    virtualFile.setContent(bb);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            } else {
                if(!entry.getName().equals(".") && !entry.getName().equals("..")) {
                    VirtualDirectory newParent = new VirtualDirectory(parent, entry.getName());
                    iterateReadDirectory(indent + 4, newParent, entry.getDirectory());
                }
            }
        }
    } 

    private void addAll(ContainerStream parentDir, FsDirectory fatDir) {
        boolean readError = false;
        for(FsDirectoryEntry e: fatDir) {
            if(e.isDirectory()) {
                try {
                    fatDir = e.getDirectory();
                }
                catch(IOException i) {
                    readError = true;
                }

                ContainerStream curr = new ContainerStream(parentDir, e.getName(), readError);
                addAll(curr, fatDir);
            }
            else {
                FsFile fatFile = null;

                try {
                    fatFile = e.getFile();
                }
                catch(IOException i) {
                    readError = true;
                }

                ByteBuffer buff = ByteBuffer.allocate((int)fatFile.getLength());

                try {
                    fatFile.read(0, buff);
                }
                catch(IOException i) {
                    readError = true;
                }

                new DocumentStream(parentDir, e.getName(), buff, readError);
            }
        }
    } 

    public CountTask(CountTaskListener listener, FsDirectory srcDir, List<String> extensions) {
        this.listener = listener;
        this.srcDir = srcDir;
        this.extensions = extensions;
    } 

    public NavigateTask(NavigateTaskListener listener, FsDirectory rootDir, String targetPath) {
        this.listener = listener;
        this.rootDir = rootDir;
        this.targetPath = targetPath;
    } 

    protected FsDirectory doInBackground(Void... params) {
        try {
            return navigate();
        } catch (Exception e) {
            Log.e("TASKS", e.getMessage(), e);
        }
        return null;
    } 

    protected void onPostExecute(FsDirectory result) {
        super.onPostExecute(result);
        listener.onNavigateReady(result);
    } 

    private FsDirectory navigate() {
        try {
            walkFileTree(rootDir, new File("/"));
        } catch (Exception e) {
            Log.e("TASKS", e.getMessage(), e);
        }
        return navigateTo;
    } 

    public void onNavigateReady(FsDirectory fromDir) {
        this.fromDir = fromDir;
        btnBackup.setEnabled(true);
        try {
            List<String> extensions = Arrays.asList(PreferenceManager.getDefaultSharedPreferences(getContext()).getString(PreferencesActivity.PREFS_EXTENSION, "").split(","));
            new CountTask(this, fromDir, extensions).execute();
        } catch (Exception e) {
            Log.e("MainActivityFragment", e.getMessage(), e);
            Toast.makeText(getContext(), R.string.mountingFailed, Toast.LENGTH_LONG).show();
        }
    } 

    private void backupFiles() {

        Context context = getContext();
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

        if (!settings.contains(PreferencesActivity.PREFS_FROM_FILE)
                || !settings.contains(PreferencesActivity.PREFS_TO_FILE)) {
            Log.e("MainActivityFragment", "Missing from/to preferences...");
            Toast.makeText(context, R.string.missingFromTo, Toast.LENGTH_LONG).show();
            btnBackup.setEnabled(false);
            return;
        }

        File to = new File(settings.getString(PreferencesActivity.PREFS_TO_FILE, ""));
        if (!to.exists()) {
            Log.e("MainActivityFragment", "Invalid from/to preferences...");
            Toast.makeText(context, R.string.invalidFromTo, Toast.LENGTH_LONG).show();
            btnBackup.setEnabled(false);
            return;
        }
        Log.i("MainActivityFragment", "Copying all files from OTG Disk to " + to);
        try {
            FsDirectory srcDir = fromDir;
            File destDir = new File(settings.getString(PreferencesActivity.PREFS_TO_FILE,
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()));
            List<String> extensions = Arrays.asList(settings.getString(PreferencesActivity.PREFS_EXTENSION, "").split(","));
            boolean delete = settings.getBoolean(PreferencesActivity.PREFS_DELETE, false);
            boolean overwrite = settings.getBoolean(PreferencesActivity.PREFS_OVERWRITE, false);
            new BackupTask(this, srcDir, destDir, extensions, delete, overwrite).execute();
        } catch (Exception e) {
            progressDialog.dismiss();
            Log.e("MainActivityFragment", e.getMessage(), e);
            Toast.makeText(context, R.string.backingUpFailed, Toast.LENGTH_LONG).show();
        }
    } 

    public void identify(final URI uri, final IdentificationRequest request) throws CommandExecutionException {

        final String newPath = makeContainerURI("fat", request.getFileName());
        setSlash1("");

        if (request.getClass().isAssignableFrom(FileSystemIdentificationRequest.class)) {

            FileSystemIdentificationRequest req = (FileSystemIdentificationRequest) request;

            try {
                FileDisk fileDisk = new FileDisk(req.getFile().toFile(), true);
                FileSystem fatSystem = FileSystemFactory.create(fileDisk, true);
                FsDirectory root = fatSystem.getRoot();
                    for (FsDirectoryEntry entry : root) {
                         processEntry(entry, uri, newPath);
                    }

            } catch (IOException e) {
                throw new CommandExecutionException("IO error in FatFileSystem", e);
            }
        } else {
            log.info("Identification request for Fat image ignored due to limited support.");
        }

    } 

    }

    protected void dumpDirectory(FsDirectory dir, int tabStop, File curDirectory, boolean hasOutputDirectory)
            throws
            IOException {
        Iterator<FsDirectoryEntry> i = dir.iterator();
        while (i.hasNext()) {
            final FsDirectoryEntry e = i.next();
            if (e.isDirectory()) {
                for (int idx = 0; idx < tabStop; idx++) {
                    System.out.print(' ');
                }
                if (e.getName().equals(".") || e.getName().equals("..")) {
                    continue;
                }
                for (int idx = 0; idx < tabStop; idx++) {
                    System.out.print("  ");
                }
                System.out.println("[" + e + "]");
                dumpDirectory(e.getDirectory(), tabStop + 1, new File(curDirectory, e.getName()),
                        hasOutputDirectory);
            } else {
                for (int idx = 0; idx < tabStop; idx++) {
                    System.out.print("  ");
                }

                System.out.println(e);

                if (!hasOutputDirectory) {
                    continue;
                }

                if (!curDirectory.exists()) {
                    if (false == curDirectory.mkdirs()) {
                        throw new IOException("Unable to create directory: " + curDirectory);
                    }
                }

                File curFile = new File(curDirectory, e.getName());
                if (curFile.exists()) {
                    throw new IOException("File exists: " + curFile);
                } else {
                    FsFile f = e.getFile();
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(curFile);
                        FileChannel outputChannel = fos.getChannel();
                        int capacity = tempBuf.capacity();
                        long length = f.getLength();
                        for (long pos = 0; pos < length; pos++) {
                            int readLength = (int) (length - pos > capacity ? capacity : length - pos);
                            tempBuf.rewind();
                            tempBuf.limit(readLength);
                            f.read(pos, tempBuf);
                            tempBuf.rewind();
                            while (tempBuf.remaining() > 0) {
                                outputChannel.write(tempBuf);
                            }
                            pos += readLength;
                        }
                    } finally {
                        if (null != fos) fos.close();
                    }
                }
            }
        }
    } 

            if (isEncrypted) {
                EncryptedBlockFile ebf = new EncryptedBlockFile(fishKey, obbInputFile, "r");
                fd = new FileDisk(ebf, ebf.getEncryptedFileChannel(), true);
            } else {
                fd = new FileDisk(obbInputFile, true);
            } 

    private void printVerboseInfo(BootSector bs, FsDirectory rootDir) {
        System.out.print("Filesystem Type: ");
        FatType ft = bs.getFatType();
        if (ft == FatType.FAT32) {
            System.out.println("FAT32");
        } else if (ft == FatType.FAT16) {
            System.out.println("FAT16");
        } else if (ft == FatType.FAT12) {
            System.out.println("FAT12");
        } else {
            System.out.println("Unknown");
        }
        System.out.print("           OEM Name: ");
        System.out.println(bs.getOemName());
        System.out.print("   Bytes Per Sector: ");
        System.out.println(bs.getBytesPerSector());
        System.out.print("Sectors per cluster: ");
        System.out.println(bs.getSectorsPerCluster());
        System.out.print("   Reserved Sectors: ");
        System.out.println(bs.getNrReservedSectors());
        System.out.print("               Fats: ");
        System.out.println(bs.getNrFats());
        System.out.print("   Root Dir Entries: ");
        System.out.println(bs.getRootDirEntryCount());
        System.out.print("  Medium Descriptor: ");
        System.out.println(bs.getMediumDescriptor());
        System.out.print("            Sectors: ");
        System.out.println(bs.getSectorCount());
        System.out.print("    Sectors Per Fat: ");
        System.out.println(bs.getSectorsPerFat());
        System.out.print("              Heads: ");
        System.out.println(bs.getNrHeads());
        System.out.print("     Hidden Sectors: ");
        System.out.println(bs.getNrHiddenSectors());
        System.out.print("         Fat Offset: ");
        System.out.println(FatUtils.getFatOffset(bs, 0));
        System.out.println("          RootDir: " + rootDir);
    } 

    public void test1() throws Exception {

        FileDisk2 f = new FileDisk2(new File("test.devofs"), false, 4096);
        DevoFSFileSystem fs = new DevoFSFileSystem(f, false);
        FsDirectory dir = fs.getRoot();
        test1_recur("", dir);
        ByteBuffer dest = ByteBuffer.allocate((int) f.getSize());
        Arrays.fill(dest.array(), (byte) 0);
        f.write(0, dest);
        fs.close();

    } 

    private void test1_recur(String indent, FsDirectory dir) {
        Iterator<FsDirectoryEntry> itr = dir.iterator();
        while (itr.hasNext()) {
            try {
                FsDirectoryEntry entry = itr.next();
                if (entry.isDirectory()) {
                    System.out.format("%sDIR: %s\n", indent, entry.getName());
                    test1_recur(indent + "    ", entry.getDirectory());
                } else {
                    System.out.format("%sFILE: %s (%d)\n", indent, entry.getName(), entry.getFile().getLength());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } 

	public static FsDirectory getFileDirectory(FileSystem fs, FileInfo file, boolean create) {
		String[]filepath = file.name().toUpperCase().split("/");
		
		String[]filedir;
		if (filepath.length > 1) {
			filedir = Arrays.copyOfRange(filepath, 0, filepath.length-1);
		} else {
			filedir = new String[0];
		}
		FsDirectory fsdir;
    	FsDirectoryEntry fs_entry;
		try {
			fsdir = fs.getRoot();
		} catch (Exception e) {
			System.err.println("Couldn't get root dir: " + e.getMessage());
			return null;
		}
        for (String subdir : filedir) {
            if (subdir.equals("")) {
               continue;
            }
            try {
            	fs_entry = fsdir.getEntry(subdir);
            	if (fs_entry == null) {
            		if (! create) {
            			return null;
            		}
            		fs_entry = fsdir.addDirectory(subdir);
            		if (fs_entry == null) {
            			System.err.println("Couldn't create directory '" + subdir);
            			return null;
            		}
            	}
            	fsdir = fs_entry.getDirectory();
            } catch (Exception e) {
            	e.printStackTrace();
            	return null;
            }
        }
		return fsdir;
	} 

	public static void copyFile(FileSystem fs, FileInfo file) {
    	FsDirectoryEntry fs_entry;
		String filename = file.baseName().toUpperCase();
		FsDirectory fsdir = getFileDirectory(fs, file, true);
		if (fsdir == null) {
			return;
		}
		try {
			fs_entry = fsdir.getEntry(filename);
			if (fs_entry == null) {
				if (file.deleted()) {
					return;
				}
				fs_entry = fsdir.addFile(filename);
				if (fs_entry == null) {
					System.err.println("Failed to create file '" + file.name());
					return;
				}
			}
			if (! fs_entry.isFile()) {
				System.err.println(file.name() + " exists but is not a file");
				return;
			}
			if (file.deleted()) {
				fsdir.remove(fs_entry.getName());
				return;
			}
			FsFile fs_file = fs_entry.getFile();
			ByteBuffer byteBuffer = ByteBuffer.allocate(file.data().length);
			byteBuffer.put(file.data());
			byteBuffer.flip();
			fs_file.write(0, byteBuffer);
			fs_entry.setLastModified(file.time());
		} catch (Exception e) {
			e.printStackTrace();
        	return;
		}
	} 

Advertisement
Javadoc
Base class for all FileSystem directories. @author Ewout Prangsma < epr at jnode.org> @author

Matthias Treydte

Read More
Advertisement