Results 1 to 7 of 7
Like Tree3Likes
  • 1 Post By jim829
  • 2 Post By kneitzel

Thread: File system in Java

  1. #1
    Doris is offline Member
    Join Date
    Feb 2014
    Posts
    2
    Rep Power
    0

    Default File system in Java

    I and a friend are working with a project to create a file system, who manages a secondary memory simulated as a byte array in Java. We want the file system to be a hierarchical tree structure like in UNIX.

    We have come quite far, but the paths are not handled correct. I seem to have mistaken the relative folder ./ for the root folder, but it should mean "working directory folder", ie, where I stand now. That is, if I stand in /dir1 as my "working directory" and make mkdir ./dir2 then should dir2 end up as subfolder in dir1. But with me it appears in the root.

    Anyone that can help me out with this?
    Attached Files Attached Files

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,001
    Rep Power
    10

    Default Re: File system in Java

    Post the code in question in the form of an SSCCE, and we'll go from there.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Doris is offline Member
    Join Date
    Feb 2014
    Posts
    2
    Rep Power
    0

    Default Re: File system in Java

    Java Code:
    public class Block
    {
    	public static final int nameSize = 32;
    	public static final int contentSize = 480;
    	
    	byte parentIndex = -128;
    	byte status = 0;
    	byte[] name = new byte[Block.nameSize];
    	byte[] content = new byte[Block.contentSize];
    
    	public Block()
    	{
    		this.parentIndex = -128;
    		this.status = 0;
    		this.name = null;
    		this.content = null;
    	}
    	
    	public Block(byte parentIndex, byte status, byte[] name, byte[] content)
    	{
    		this.parentIndex = parentIndex;
    		this.status = status;
    		this.name = name;
    		this.content = content;
    	}
    
    	public byte getParentIndex(){return parentIndex;}
    	public void setParentIndex(byte parentIndex){this.parentIndex = parentIndex;}
    	public byte getStatus(){ return status; }
    	public void setStatus(byte status) { this.status = status; }
    	public byte[] getName(){return name;}
    	public void setName(byte[] name) {this.name = name;}
    	public byte[] getContent(){return content;}
    	public void setContent(byte[] content){this.content = content;}
    	public static int getNamesize() {return nameSize;}
    }
    Java Code:
    public class Filesystem
    {
    	private MemoryBlockDevice m_BlockDevice;
    	private int pwdBlockIndex;
    
    	public Filesystem()
        {
    		this.m_BlockDevice = new MemoryBlockDevice();
    		this.pwdBlockIndex = 0;
        }
    
    	public String ls(String[] path)
        {
    		System.out.println("Listing directory ");
    		
    		try
    		{
    			byte directoryBlockIndex = this.findBlockIndex(path);
    			if(this.m_BlockDevice.readBlock(directoryBlockIndex+128).getStatus() != 2)
    				throw new Exception("Path is not a folder");
    			
    			byte[] children = this.findChildrenOfParent(directoryBlockIndex);
    			
    			String outString = "";
    			
    			for(int i = 0; i < children.length; i++)
    			{
    				Block block = this.m_BlockDevice.readBlock(children[i]+128);
    				outString += new String(block.getName()) + "\n";
    			}
    			
    			return outString;
    		}
    		catch(Exception e)
    		{
    			return e.getMessage();
    		}
        }
    	
    	public String mkdir(String[] path)
        {
    		System.out.println("Creating directory ");
    		
    		byte directoryBlockIndex;
    		try
    		{
    
    			int emptyBlock = this.findFirstEmptyBlock();
    			if(emptyBlock == -1)
    				return "Filesystem is full";
    			
    			directoryBlockIndex = this.findBlockIndex(Arrays.copyOfRange(path, 0, path.length-1));
    			Block directoryBlock = this.m_BlockDevice.readBlock(directoryBlockIndex+128);
    			if(directoryBlock.getStatus() != 2) //if block is not a folder, return
    	    	  return "Path is not a directory";
    			
    			byte[] filename = path[path.length-1].getBytes();
    			Block newBlock = new Block(directoryBlockIndex, (byte) 2, filename, null);
    			this.m_BlockDevice.writeBlock(emptyBlock, newBlock);
    	      
    			return "Success";
    		}
    		catch (Exception e)
    		{
    			return e.getMessage();
    		}
    	}
      
      	public String cd(String[] path)
        {
      		System.out.println("Changing directory to ");
    
      		try
      		{
      			if(path[0].equals(".."))
      				this.pwdBlockIndex = this.m_BlockDevice.readBlock(this.pwdBlockIndex).getParentIndex()+128;
      			else
      				this.pwdBlockIndex = this.findBlockIndex(path)+128;
    		}
      		catch (Exception e)
      		{
    			System.out.println(e.getMessage());
    		}
      		
      		return new String("Success");
        }
    
      	public String pwd() throws Exception
        {
    		String output = "";
    		ArrayList<Byte> path = new ArrayList<Byte>();
      		Block block = this.m_BlockDevice.readBlock(this.pwdBlockIndex);
      		byte[] name = block.getName();
    
      		if(this.pwdBlockIndex != 0)
      		{
    	  		this.findAbsolutePath(path, block);
    	  		for(int i = path.size()-1; i >= 0; i--)
    	  		{
    	  			Block currentBlock = this.m_BlockDevice.readBlock(path.get(i)+128);
    	  			output += new String(currentBlock.getName()).trim() + "/";
    	  		}
      		}
      		output += new String(name);
      		
      		return output.trim();
        }
      
      	private Byte findBlockIndex(String[] path) throws Exception
      	{
      		Byte root = -128;
      		return this.findIndexOfChild(root, path);
      	}
      
      	private Byte findIndexOfChild(Byte parent, String[] path) throws Exception
      	{
      		boolean found = false;
      		int counter = 0;
      		Byte index = -128;
      		Byte parentIndex = -128;
      		while(counter < MemoryBlockDevice.numberOfBlocks && !found)
      		{
      			Block block = this.m_BlockDevice.readBlock(counter);
      			byte[] name = block.getName();
      			parentIndex = block.getParentIndex();
    			
      			if(parentIndex == parent && path[0].equals(new String(name).trim()))
      				found = true;
      			else
      			{
      				counter++;
      				index++;
      			}
      		}
      		
      		if(!found)
      			throw new Exception("File does not exist");
      		
      		if(path.length == 1)
      			return index;
      		else
      		{
      			String[] newPath = Arrays.copyOfRange(path, 1, path.length);
      			return this.findIndexOfChild(index, newPath);
      		}
      	}
      	
      	private byte[] findChildrenOfParent(Byte parent) throws Exception
      	{
      		ArrayList<Byte> children = new ArrayList<Byte>();
      		
      		int counter = 0;
      		Byte index = -128;
      		while(counter < MemoryBlockDevice.numberOfBlocks)
      		{
      			Block block = this.m_BlockDevice.readBlock(counter);
      			Byte parentIndex = block.getParentIndex();
    			
      			if(parentIndex == parent && block.getStatus() != 0)
      				children.add(index);
    
    			counter++;
    			index++;
      		}
      		
      		if(children.isEmpty())
      			throw new Exception("Folder is empty");
      		
      		byte[] outChildren = new byte[children.size()];
      		for(int i = 0; i < children.size(); i++)
      			outChildren[i] = children.get(i);
      		
      		return outChildren;
      	}
      	
      	private int findFirstEmptyBlock() throws Exception
      	{
      		boolean found = false;
      		int index = 0;
      		Byte typeBlock = -128;
      		while(index < MemoryBlockDevice.numberOfBlocks && !found)
      		{
      			Block block = this.m_BlockDevice.readBlock(index);
      			typeBlock = block.getStatus();
    			  
      			if(typeBlock == 0)
      				found = true;
      			else
      				index++;
      		}
    	  
      		if(found)
      			return index;
      		else
      			return -1;
      	}
      	
      	private void findAbsolutePath(ArrayList<Byte> path, Block block) throws Exception //TODO Exception message
      	{
      		byte parentIndex = block.getParentIndex();
    		path.add(parentIndex);
      		if(parentIndex != -128)
      		{
      			Block parent = this.m_BlockDevice.readBlock(parentIndex);
      			this.findAbsolutePath(path, parent);
      		}
      	}
    }
    Java Code:
    public class MemoryBlockDevice
    {
    	public static final int numberOfBlocks = 256;
    	Block[] blocks = new Block[MemoryBlockDevice.numberOfBlocks];
    	
    	public MemoryBlockDevice()
    	{
    		for(int i = 0; i < MemoryBlockDevice.numberOfBlocks; i++)
    				this.blocks[i] = new Block();
    		
    
    		byte[] name = new byte[Block.nameSize];
    		name[0] = 46;
    		Block root = new Block((byte) -128, (byte) 2, name, null);
    
    		try
    		{
    			this.writeBlock(0, root);
    		}
    		catch (Exception e)
    		{
    		}
    	}
    	
    	public void writeBlock(int index, Block block) throws Exception
        {
    		if(index > MemoryBlockDevice.numberOfBlocks-1 || index < 0)
    	    	  throw new Exception("Block out of range while writing");
    
    		this.blocks[index] = block;
        }
    
    	public Block readBlock(int index) throws Exception
        {
          if(index > MemoryBlockDevice.numberOfBlocks-1 || index < 0)
        	  throw new Exception("Block out of range while reading");
    
          return this.blocks[index];
        }
    	
    	public void print(int from, int to)
    	{
    		for(int i = from; i < to; i++)
    		{
    			Block block = this.blocks[i];
    			if(block.getName() == null)
    				System.out.println("Block #" + i + " -- Parent at " + block.getParentIndex() + " -- Type is " + block.status + " -- Name is null ");
    			else
    				System.out.println("Block #" + i + " -- Parent at " + block.getParentIndex() + " -- Type is " + block.status + " -- Name is: " + new String(block.getName()).trim());
    		}
    	}
    }
    Java Code:
    public class Shell
    {
    	private Filesystem m_Filesystem;
    	private InputStream m_Stream;
    
    	public Shell(InputStream p_Stream)
    	{
    		m_Filesystem = new Filesystem();
    
    		if(p_Stream==null)
    			m_Stream=System.in;
    		else
    			m_Stream=p_Stream;
        }
    
    	public void start()
        {
          String[] asCommands = { "quit","format","ls","create","cat","save","read",
                                  "rm","copy","append","rename","mkdir","cd","pwd","help"};
    
          boolean bRun=true;
          String  sCommand;
          String[] asCommandArray;
    
          while(bRun)
          {
        	  try
        	  {
    	    	  System.out.print("["+m_Filesystem.pwd()+"]$ ");
    	          sCommand=readLine().trim();
    	          asCommandArray=split(sCommand,' ');
    	          if(asCommandArray.length > 0)
    	          {
    	        	  int nIndex;
    	        	  for(nIndex=0;nIndex<asCommands.length;nIndex++)
    	        	  {
    	        		  if(asCommandArray[0].compareTo(asCommands[nIndex])==0)
    	        			  break;
    	        	  }
    	        	  
    	              switch(nIndex)
    	              {
    	              	case 0: // quit
    	              		return;
    	              	case 1: // format
    	              		break;
    	                case 2: // ls
    	                	if(asCommandArray.length==1)
    	                		System.out.println(m_Filesystem.ls(split(this.m_Filesystem.pwd(),'/')));
    	                	else
    	                		if(asCommandArray.length!=2)
    	                			System.out.println("Usage: ls <path>");
    	                		else
    	                			System.out.println(m_Filesystem.ls(split(asCommandArray[1],'/')));
    	                	break;
    	                case 11: // mkdir
    	                	if(asCommandArray.length!=2)
    	                		System.out.println("Usage: mkdir <directory name>");
    	                	else
    	                		System.out.println(m_Filesystem.mkdir(split(asCommandArray[1],'/')));
    	                	break;
    	                case 12: // cd
    	                	if(asCommandArray.length!=2)
    	                		System.out.println("Usage: cd <path>");
    	                	else
    	                	  	System.out.println(m_Filesystem.cd(split(asCommandArray[1],'/')));
    	                	break;
    	                case 13: // pwd
    	                	if(asCommandArray.length!=1)
    	                		System.out.println("Usage: pwd");
    	                	else
    	                	{
    	                		try
    	                		{
    	                    	  	System.out.println(m_Filesystem.pwd());
    	                		}
    	                		catch(Exception e)
    	                		{
    	                			System.out.println(e.getMessage());
    	                		}
    	                	}
    	                	break;
    	                default:
    	                	System.out.println("Unknown command "+asCommandArray[0]);
    	              }
    	          }
        	  }
        	  catch(Exception e)
        	  {
        		  System.out.println(e.getMessage());
        		  bRun = false;
        	  };
          }
        }
    	
    	private String[] split(String p_sString,char p_cDel) 
      	{
      		java.util.StringTokenizer st = new java.util.StringTokenizer(p_sString,
      																						 p_cDel + "");
    		
      		int nrOfTokens = st.countTokens();
      		String[] asStrings = new String[nrOfTokens];
    		
      		int nr = 0;
      		while(st.hasMoreTokens())
      		{
      			asStrings[nr] = st.nextToken();
      			nr++;
      		}
      		return asStrings;
      	}
    	
    	private String readLine()
        {
    		byte[] abTempBuffer=new byte[480];
    		byte bTemp;
    		int nIndex=0;
    		
    		for(nIndex=0;nIndex<480;nIndex++)
            {
    			try
                {
    				bTemp=(byte)m_Stream.read();
                }
    			catch(IOException io)
                {
    				bTemp='\n';
                }
    			
    			if(bTemp=='\n' || bTemp=='\r')
                {
    				break;
                }
    			abTempBuffer[nIndex]=bTemp;
    		}
    		String sTemp=new String(abTempBuffer,0,nIndex);
    		sTemp=sTemp.trim();
    		return sTemp;
    	}
    	
    	private byte[] readBlock()
    	{
    		byte[] abTempBuffer=new byte[480];
    		byte bTemp;
    		int nIndex=0;
    		boolean bEnter=false;
    		
    		for(nIndex=0;nIndex<480;nIndex++)
    		{
    			try
    			{
    				bTemp=(byte)m_Stream.read();
    			}
    			catch(IOException io)
    			{
    				bTemp='?';
    			}
    			
    			if(bTemp=='\n' || bTemp=='\r')
    			{
    				if(bEnter)
    					break;
    				else
    					bEnter=true;
    				}
    			else
    				bEnter=false;
    			
    			abTempBuffer[nIndex]=bTemp;
    		}
    		return abTempBuffer;
    	}
    
    	private void printHelp()
    	{
    	      System.out.println("OSD Disk Tool");
    	      System.out.println("-----------------------------------------------------------------------------------");      
    	}
    }
    Java Code:
    public class TestShell
    {
    	public static void main(String[] args)
        {
    		Shell Bash=new Shell(null);
    		Bash.start();
        }
    }

  4. #4
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: File system in Java

    Hi,

    I just had a quickl look but I do not see the place where you handle the "." as special directory. So you need to think about your design and implement that handling. (So you already have a handling of ".." in your code to get the parent. But you should also rethink about the design in that point, because you need this handling everywhere. So a path like ../somedir/../../adir/./.././againSomeDir could be valid.

    Also one thing I don't understand: A directory entry is simply using a block? That is something wired. If you check out existing filesystems then you will see that blocks are just space of the disk. Some blocks are used to store directory content. This oculd be inodes. Of course they occupy some blocks but not each entry takes a block.

    With kind regards,

    Konrad

  5. #5
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,813
    Rep Power
    5

    Default Re: File system in Java

    That is not an SSCCE as requested. The operative word in this case is short.

    Regards,
    Jim
    KevinWorkman likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,619
    Rep Power
    25

    Default Re: File system in Java

    One major problem I see with the code: There are no comments in the code that document what the code is supposed to do and how it is going to do it.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    kneitzel is offline Senior Member
    Join Date
    Feb 2014
    Posts
    447
    Rep Power
    1

    Default Re: File system in Java

    Yeah,

    Norm is correct. But I want to extend it a little bit:

    a) Documentation in code is simply a must do. You should even read about javadoc so you can generate some nice documentation!

    b) But you should even document yourself what you want to implement. Do not sit in front of the computer and start coding. Get a plan first! Without that you cannot expect any results at all (ok, a hello world application might be possible!).

    And if you got that start; Lokk at some IDE with integrated debugger. Start debugging your application. And check step by step if your code is doing what you expect and if you get exactly the results that you want.

    I do not want to get you sad. I think you are a beginner and I really want to help you. So I got the zip and played around with it but sorry: The mentioned problem is just the smallest one at all. I got the understanding, that something might work already if you got such a specific problem. But sorry - playing around simply showed nothing that seems to work (So I always got a Success on my cd but the prompt always was [.]$ )

    So how can I try to assist you? Maybe I simply try to give you a small description how development could work:
    a) Get a real plan. That simply means, that you think about the object model. Try to imagine real objects. Put stuff where it really belongs to. (So to take your code as example: The current working directory does not belong to a filesystem. It belongs to a process. So your shell has a current directory!) So if you want to have some kind of FileSystem you should really think about the different objects that you have.
    - Blocks are just a sequenze of blocks on a medium. They are normaly used with direct access which is a low leven thing. You can read a block with a call like "get data of block 1278"
    - You now want to maintain blocks. You can have a partition schema. Ok, You maybe decide to skip that part. But you could define that the first block contains information about the usage of other blocks. So you could have a list of free blocks, a list of faulty blocks, some content system....
    - To store the content you have something like file system entries. These store some information e.g. name, owner, timestamps, link to blocks ... You might want to have code to read and write this information to the blocks.
    - ....
    Play around with it on paper. Just get some blank sheets of paper and write down what you want to have (e.g. blocks with bytes on it) and then play around to see if you can do everything you want to do. E.g. write in the first block what information you want to have there. Perform operations e.g. "Format" the available blocks, add a file, add a directory, ...
    - If you have something like that you could try to divide it in parts. Try to build it in multiple small parts. Don't create the whole world. Start with small pieces and put them together. So you could start writing the maintenance of blocks. So maybe you have a class Block which can be initialized with a blocksize. You could create a class disk which has an array of Blocks. You can provide the functions required to read and write data.
    Important: Test that carefully! (Maybe you even want to check out a framework like junit!) When that job is done you proceed with the next part! (You cannot work on a filesystem if you only have a broken disk!)

    Not sure if that helped. But right now I do not see a better way to help. My experience is that it is best to have someone experienced who can guide you. So maybe there is someone experienced who could talk with you about your object model (I hope you have one. If not: Take a piece of paper and start drawing with a pencil! :) ).

    With kind regards,

    Konrad
    Norm and AlexGraal like this.

Similar Threads

  1. Replies: 0
    Last Post: 12-15-2012, 02:37 AM
  2. Replies: 6
    Last Post: 11-24-2011, 03:03 AM
  3. Replies: 4
    Last Post: 10-30-2010, 11:16 AM
  4. How to read xml file located in local system using Java
    By java_kick in forum Advanced Java
    Replies: 2
    Last Post: 04-07-2009, 12:28 AM
  5. where i put my jar file in my system?
    By makpandian in forum New To Java
    Replies: 11
    Last Post: 02-11-2009, 05:51 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •