All pastes #927765 Raw Edit

Something

public text v1 · immutable
·published 2008-03-04 15:14 UTC
rendered paste body
package oving6;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.MalformedURLException;

import com.sun.org.apache.xerces.internal.util.URI.MalformedURIException;

public class ColonyIO {
	
	public static Colony readColony(File file) throws IOException {
		return ColonyIO.readColony(new BufferedReader(new FileReader(file)));
	}
	
	public static Colony readColony(URI url) throws IOException {
		InputStream is = null;
		BufferedReader br = null;
		
		try {
			is = url.toURL().openStream();
			br = new BufferedReader(new InputStreamReader(is));
		} catch (MalformedURLException murle) {
			System.err.println(murle);
		} catch (IOException ioe) {
			System.err.println(ioe);
		}
		
		return ColonyIO.readColony(br);

		
	}
	
	public static Colony readColony(BufferedReader br) throws IOException {
		
		if (!br.ready()) throw new IOException("Error: Buffer not ready.");
		if (br == null) throw new IOException("Error: Buffer is empty.") ;
		
		try {
			
			String currentLine = br.readLine();
			String[] temp = currentLine.split("x");
			int width = Integer.parseInt(temp[0]);
			int height = Integer.parseInt(temp[1]);
			Colony colony = new BooleanArrayColony(height, width);
			int widthCounter = 0;
			
			do {
				currentLine = br.readLine();
				
				if (currentLine.startsWith("#")) {
					continue;
				} else if (isValid(currentLine)) {
					char[] c = new char[currentLine.length()];
					for (int i = 0; i < currentLine.length(); i++) {
						char cTemp;
						cTemp = currentLine.charAt(i);
						c[i] = cTemp;
						boolean state = false;
						if (c[i] == '*') state = true;
						colony.setCell(i, widthCounter, state);
					}
					continue;
				} else if (!isValid(currentLine)) {
					break;
				}
				widthCounter++;
				
			} while (currentLine != null);
			
			return colony;
			
		} catch (IOException ioe) {
			System.err.println(ioe);
		} catch (IllegalArgumentException iae) {
			System.err.println(iae);
		}
		
		
		return null;
	}
	
	private static boolean isValid(String s) {
		for (int i = 0;i < s.length();i++) {
			char c = s.charAt(i);
			if (Character.isDigit(c) || Character.isWhitespace(c) || c == 'x') {
				continue;
			} else {
				return false;
			}
		}
		return true;
	}
	
}