Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: can't add a file

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    21
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default can't add a file

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.*;
    import java.util.concurrent.*;
    import java.util.AbstractCollection;
     
    public class Wiki {
     
    	// private ConcurrentHashMap<String, SynchronizedStack<TXTFile>> repository;
    	private ConcurrentHashMap<String, Stack<TXTFile>> repository;
     
    	public Wiki() {
    		// repository = new ConcurrentHashMap<String,
    		// SynchronizedStack<TXTFile>>();
    		repository = new ConcurrentHashMap<String, Stack<TXTFile>>();
    	}
     
    	// HashMap to store files
    	private HashMap<String, TXTFile> files;
     
    	/**
    	 * Method used to wait for input and invoke methods according to that input.
    	 */
    	public void Start()
    	{
    		System.out.println("Wiki started");
    		String input = "";
    		Scanner in = new Scanner(System.in);
    		// Create the txt_files folder if it does not already exist.
    		File dir = new File("txt_files");
    		if(! dir.exists())
    		{
    			dir.mkdir();
    		}
     
    		// Enter a loop to parse all input.
    		do{
    			System.out.println(">");
    			input = in.nextLine();
     
    			// Perform string matching
    			/*if(input.startsWith("commit"))
    			{
    				commit();
    				continue;
    			}*/
     
    			if(input.startsWith("add"))
    			{
    				/* "\\s+" this groups all whitespaces as a delimiter... so if i have the 
    				   string "Hello[space][tab]World", this should yield the strings 
    				   "Hello" and "World" and omit the empty space between the space and the tab*/
    				Add(input.substring(4).split("\\s+"));
    				continue;
    			}
     
     
    			if(input.equals("show"))
    			{
    				list();
    				continue;
    			}
     
    			// Fall through case
    			System.out.println("Illegal command: " + input);
     
     
    		}while(!input.equals("quit"));
    		// Cleanup.
    		System.out.println("Wiki is terminating...");
    		in.close();		
    	}
     
    	/**
    	 * Method used for listing all wiki files.
    	 */
    	public void list() {
    		File dir = new File("txt_files");
    		File[] wfiles = dir.listFiles();
    		// No files in directory.
    		if (wfiles == null) {
    			// return;
    			System.out.println("There no files !");
    		}
    		// Initialise streams
    		FileInputStream fis = null;
    		BufferedInputStream bis = null;
    		BufferedReader reader = null;
     
    		// Loop over all files in the directory.
    		for (File f : wfiles) {
    			// System.out.println(f.getName().endsWith(".txt"));
    			System.out.println(f.getName());
    		}
    	}
     
    	/**
    	 * Method used for outputting the content of wiki files.
    	 */
    	/*
    	 * private void list() { File dir = new File("txt_files"); File[] wfiles =
    	 * dir.listFiles(); // No files in directory. if(wfiles == null) { return; }
    	 * // Initialise streams FileInputStream fis = null; BufferedInputStream bis
    	 * = null; BufferedReader reader = null;
    	 * 
    	 * // Loop over all files in the directory. for(File f : wfiles) {
    	 * if(f.getName().endsWith(".txt")) { try{ fis = new FileInputStream(f); bis
    	 * = new BufferedInputStream(fis); reader = new BufferedReader(new
    	 * InputStreamReader(bis)); String entry;
    	 * 
    	 * while ((entry = reader.readLine()) != null) {
    	 * System.out.println(f.getName().substring(0, f.getName().indexOf(".")) +
    	 * "\t" + entry); }
    	 * 
    	 * }catch(Exception e){ e.printStackTrace(); }finally{ try{ fis.close();
    	 * bis.close(); reader.close(); }catch(IOException e) {
    	 * System.out.println("Error closing streams!"); e.printStackTrace(); } } }
    	 * } System.out.println(); }
    	 */
     
    	// ?? load factor = initial-capacity x .75 = number of items (round up) that
    	// HashMap supports
    	/*
    	 * commit method is used before adding a file to the repository if accepted
    	 * version < Wiki's newest version, an Exception is thrown HashMap contains
    	 * all files which will be added to the repository
    	 */
     
    	/*
    	 * public void commit(HashMap<String, TXTFile> files) throws Exception{
    	 * Iterator<String> keySet = files.keySet().iterator(); while
    	 * (keySet.hasNext()) { TXTFile file = files.get(keySet.next()); add(file);
    	 * } }
    	 */
     
    	/**
    	 * Adds a file to the repository (1).
    	 */
    	public void Add(String[] tokens) {
    		if (tokens.length < 2) {
    			System.out.println("Illegal arguments");
    			System.out.println("add [file_name] [content]");
    			System.out.println();
    			return;
    		}
    		// processing user input, creating a TXTFile
    		String fileName = tokens[0];
    		String content = tokens[1];
    		TXTFile file = new TXTFile(fileName, content);
     
    		// managing file versions
    		Stack<TXTFile> stack = repository.get(file.getFileName());
    		if (stack == null) // if there are no versions yet
    		{
    			stack = new Stack<TXTFile>();
    			file.setVersion(1);
    			TXTFile copy = file.clone();
    			stack.push(copy);
    			repository.put(file.getFileName(), stack);
    		}
     
    		else {
    			int subVersion = file.getVersion();
    			int latestVersion = stack.peek().getVersion();
     
    			/*
    			 * if(subVersion == -1) throw new Exception(
    			 * "Your file has no Version yet. You need to checkout or update before submitting files"
    			 * );
    			 * 
    			 * if(subVersion < latestVersion || subVersion > latestVersion)
    			 * throw new Exception("Your file \"" +file.getFileName()
    			 * +"\" has an outdated or not allowed version");
    			 */
     
    			file.setVersion(++latestVersion);
    			stack.push(file.clone());
    		}
     
    	}
     
     
     
     
     
     
    	/**
    	 * Adds a file to the repository (2).
    	 */
    	/*
    	 * public void add(TXTFile file) throws Exception { if
    	 * (file.getFileName().length() < 1) throw new Exception("No FileName !");
    	 * 
    	 * //SynchronizedStack<TXTFile> stack = repository.get(file.getFileName());
    	 * Stack<TXTFile> stack = repository.get(file.getFileName());
    	 * 
    	 * if(stack == null) { //stack = new SynchronizedStack<TXTFile>(); stack =
    	 * new Stack<TXTFile>(); file.setVersion(0); TXTFile copy =
    	 * file.clone(file); stack.push(file.clone(file));
    	 * repository.put(file.getFileName(), stack); }
    	 * 
    	 * else { int subVersion = file.getVersion(); int latestVersion =
    	 * stack.peek().getVersion();
    	 * 
    	 * if(subVersion == -1) throw new Exception(
    	 * "Your file has no Version yet. You need to checkout or update before submitting files"
    	 * );
    	 * 
    	 * if(subVersion < latestVersion || subVersion > latestVersion) throw new
    	 * Exception("Your file \"" +file.getFileName()
    	 * +"\" has an outdated or not allowed version");
    	 * 
    	 * file.setVersion(++latestVersion); stack.push(file.clone(file)); } }
    	 */
     
    	// removes a file from the repository
    	public void remove(String fileName) throws Exception {
    		if (!repository.containsKey(fileName))
    			throw new Exception("The file \"" + fileName
    					+ "\" doesnt exist in the Repository");
     
    		repository.remove(fileName);
    	}
     
    	// Update method to update a single file to the newest version available
    	public TXTFile update(String filename) throws Exception {
    		if (!repository.containsKey(filename))
    			throw new Exception("The file \"" + filename
    					+ "\" doesnt exist in the Repository");
     
    		// SynchronizedStack<TXTFile> stack = repository.get(filename);
    		Stack<TXTFile> stack = repository.get(filename);
     
    		TXTFile file = stack.peek();
     
    		//try {
    			return file.clone();
    		//} catch (CloneNotSupportedException ex) {
    		//	return null;
    		//}
    	}
     
    	// Reverts a single file to the version given as parameter
    	public TXTFile revert(String filename, int version) throws Exception {
    		if (!repository.containsKey(filename))
    			throw new Exception("The file \"" + filename
    					+ "\" doesnt exist in the Repository");
     
    		// SynchronizedStack<JavaCode> stack = repository.get(filename);
    		Stack<TXTFile> stack = repository.get(filename);
     
    		if (version < 0 || version >= stack.size())
    			throw new Exception("Please check your version. Your Version: \""
    					+ version + "\"");
     
    		TXTFile file = stack.get(version);
     
    		Boolean found = false;
    		if (file.getVersion() != version) {
    			Iterator<TXTFile> iterator = stack.iterator();
     
    			while (iterator.hasNext())
    				if (iterator.next().getVersion() == version) {
    					found = true;
    					break;
    				}
    			if (!found)
    				throw new Exception("The version \"" + version
    						+ "\" of the file \"" + filename
    						+ "\" doesn't exist in the Repository");
    		}
     
    		return file.clone();
    	}
     
    }

    public class TXTFile {
     
    	private String fileName;
    	private int version;
    	private String content;
     
    	public TXTFile(String fileName, String content){
    		this.fileName = fileName;
    		this.content = content;
    	}
     
    	public int getVersion() {
    		return this.version;
    	}
     
    	public void setVersion(int version) {
    		this.version = version;
    	}
     
    	public TXTFile(String fn){
    		this.fileName = fn;
    	}
     
    	public String getFileName() {
    		return this.fileName;
    	}
     
    	public void setFileName(String fileName) {
    		fileName = fileName;
    	}
     
    	@Override public TXTFile clone(){
    		try{
    			return (TXTFile) super.clone();
    		} catch (CloneNotSupportedException e){
    			throw new AssertionError();
    		}
    	}
     
    	/*public TXTFile clone(TXTFile file) throws CloneNotSupportedException{
    		return (TXTFile)file.clone();
    	}*/
     
    	public String getContent() {
    		return this.content;
    	}
     
    	public void setContent(String cont) {
    		this.content = cont;
    	}
     
     
    }

    public class Main {
    	public static void main(String[] args) {
     
    		// Start Wiki
    		Wiki wiki = new Wiki();
    		wiki.Start();
     
    	}
     
    }

    Console output:
    Wiki started
    >
    show
    handler copy 2.txt
    handler copy.txt
    handler.txt
    >
    add example.txt content
    Exception in thread "main" java.lang.AssertionError
    at TXTFile.clone(TXTFile.java:37)
    at Wiki.Add(Wiki.java:163)
    at Wiki.Start(Wiki.java:59)
    at Main.main(Main.java:6)

    what's wrong ?


  2. #2
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: can't add a file

    Clone is not supported on File...

    You might want to look at the java.io package, linked below, in more detail

    java.io (Java Platform SE 7 )

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: can't add a file

    Have you tried implementing the cloneable interface?
    read the API doc for the cloneable interface.

Similar Threads

  1. Replies: 3
    Last Post: December 2nd, 2011, 11:53 AM
  2. Replies: 10
    Last Post: January 12th, 2011, 05:48 AM
  3. insert(embed) a file object (.txt file) in MS excel sheet using java.
    By jyoti.dce in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 12th, 2010, 08:16 AM
  4. Inputing file (.txt) and finding the highest number in the file
    By alf in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 15th, 2010, 09:11 AM
  5. Replies: 8
    Last Post: January 6th, 2010, 09:59 AM