⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filehandler.java

📁 Java source code for the Ant Colony Optimization Problem.
💻 JAVA
字号:
package jwo.jpss.spatial;    // Part of the spatial modelling package.
import java.io.*;            // For file handling.
import java.util.*;          // For string tokenizer.
import jwo.jpss.utilities.*; // For XML processor.
			
//  **************************************************************
/** Provides a series of static methods for handling GIS files.
  * @author Jo Wood.
  * @version 2.2, 11th October, 2001
  */
//  **************************************************************

public class FileHandler
{   
    // -------------------- Class variables ----------------------

                  /** Unknown file format. */
    public static final int UNKNOWN = 1;
                  /** Internal file format. */
    public static final int INTERNAL = 1;
                  /** ArcGrid ASCII raster format. */
    public static final int ARC_GRID_ASCII = 2;
                  /** Generic ASCII vector format. */
    public static final int VECTOR_ASCII = 3;
                  /** XML Vector format. */
    public static final int XML_VECTOR = 4;
    
    // ----------------------- Methods ---------------------------
   
    /** Attempts to read the given spatial file.
      * @param inFile File to read.
      * @return SpatialObject containing read file or null if not read.
      */
    public static SpatialObject readFile(File inFile)
    {
    	int fileType = guessFileType(inFile.getName());
        return readFile(inFile,fileType);
    }  

    /** Attempts to read the given spatial file of the given type.
      * @param inFile File to read.
      * @param fileType Type of file to read.
      * @return SpatialObject containing read file or null if not read.
      */
    public static SpatialObject readFile(File inFile, int fileType)
    {
    	switch (fileType)
        {
            case(INTERNAL):
                return readInternal(inFile);
            case(ARC_GRID_ASCII):
                return readArcGrid(inFile);
            case(VECTOR_ASCII):
                return readVectText(inFile);
            case(XML_VECTOR):
                return readXMLVect(inFile);
            default:
                return null;
        }
    } 

    /** Attempts to save the given spatial object as the given file.
      * @param spObject Spatial object to save.
      * @param outFile File name to save.
      * @return true if saved correctly.
      */
    public static boolean saveFile(SpatialObject spObject, File outFile)
    {
        int fileType = guessFileType(outFile.getName());
        return writeFile(spObject,outFile,fileType);
    }  

    /** Attempts to save the given spatial object in the given 
      * file format with the given file name.
      * @param spObject Spatial object to save.
      * @param outFile File name to save.
      * @return true if saved correctly.
      */
    public static boolean writeFile(SpatialObject spObject,
                                    File outFile, int fileType)
    {
    	switch (fileType)
        {
            case(INTERNAL):
                return writeInternal(spObject, outFile);
            case(XML_VECTOR):
                return writeXMLVect(spObject, outFile);
            default:
                return false;
        }
    } 
 
    /** Attempts to predict the type of file based on its extension.
      * @param fileName Name of file to guess.
      * @return Type of file, or UNKNOWN if not known.
      */
    public static int guessFileType(String fileName)
    {
        // Find file filename extension.
        int i = fileName.lastIndexOf('.');

        if ((i <= 0) || (i > fileName.length()-1))
            return UNKNOWN;    // No filename extension.
       
        String ext = fileName.substring(i+1);

        if (ext.equalsIgnoreCase("gis"))
            return INTERNAL;
        if (ext.equalsIgnoreCase("grd"))
            return ARC_GRID_ASCII;
        if (ext.equalsIgnoreCase("txt"))
            return VECTOR_ASCII; 
        if (ext.equalsIgnoreCase("xml"))
            return XML_VECTOR; 

        return UNKNOWN;
    } 

    // -------------------- Private Methods ---------------------
    
    /** Attempts to save the given spatial object as the given file.
      * @param spObject Spatial object to save.
      * @param outFile File name to save.
      * @return true if saved correctly.
      */
    private static boolean writeInternal(SpatialObject spObject, File outFile)
    {
        try
        {                    
            FileOutputStream oStrm = new FileOutputStream(outFile);
            BufferedOutputStream oBStrm =new BufferedOutputStream(oStrm);
            ObjectOutput oOStrm = new ObjectOutputStream(oBStrm);

            oOStrm.writeObject(spObject);
            oOStrm.flush();           
            oOStrm.close();
        }
        catch (FileNotFoundException e) { System.out.println(e);return false; }
        catch (IOException e) { System.out.println(e); return false; }
   
    	return true;
    }  

    /** Attempts to read the given file representing a serialized object.
      * @param inFile File to read.
      * @return SpatialObject containing read file or null if not read.
      */
    private static SpatialObject readInternal(File inFile)
    {
        SpatialObject spObject;

        try
        {
            FileInputStream iStrm = new FileInputStream(inFile);
            BufferedInputStream iBStrm = new BufferedInputStream(iStrm);
            ObjectInput iOStream = new ObjectInputStream(iBStrm);

            spObject = (SpatialObject)(iOStream.readObject());
            iOStream.close();
        }
        catch (IOException e) {System.out.println(e);return null;}
        catch (ClassNotFoundException e) {System.out.println(e);return null;}
        catch (ClassCastException e) {System.out.println(e);return null;}

    	return spObject;
    }  

    /** Attempts to read the given file representing an ArcGrid raster.
      * @param inFile File to read.
      * @return SpatialObject containing read file or null if not read.
      */
    private static SpatialObject readArcGrid(File inFile)
    {
        RasterMap rasterMap;

        try
        {
            BufferedReader bInFile = new BufferedReader(new FileReader(inFile));
            String line, word;        // Stores line/word of file
            StringTokenizer sToken;   // Reads in word at a time
        
            float south=0, west =0, resoln=1, noData=Float.MAX_VALUE;
            int   nRows=0, nCols=0;
           	    
            while (true)
            {
                line = bInFile.readLine();
    	        sToken = new StringTokenizer(line);
                word = sToken.nextToken().toUpperCase();

                if (word.startsWith("NCOL"))
                    nCols = Integer.parseInt(sToken.nextToken());
                else if (word.startsWith("NROW"))
                    nRows = Integer.parseInt(sToken.nextToken());
                else if (word.startsWith("XLLCORNER"))
                    west = Float.valueOf(sToken.nextToken()).floatValue();
                else if (word.startsWith("YLLCORNER"))
                    south = Float.valueOf(sToken.nextToken()).floatValue();
                else if (word.startsWith("CELLSIZE"))
                    resoln = Float.valueOf(sToken.nextToken()).floatValue();
                else if (word.startsWith("NODATA"))
                    noData = Float.valueOf(sToken.nextToken()).floatValue();
                else
                    break;    // No more header.
            }

            // Create header and RasterMap.
            Header header = new Header(inFile.getPath(),"Unknown","Unknown",                
                                       "Imported from ArcGrid ASCII file");
            rasterMap = new RasterMap(nRows,nCols,resoln,
                                      new Footprint(west,south),header);
            
            sToken = new StringTokenizer(line);

            // Read in body of raster.
            for (int row=0; row<nRows; row++)
            {
                for (int col=0; col<nCols; col++)
                {
                    // Read in a new line if we have run out of tokens.
                    if (!sToken.hasMoreTokens())
                        sToken = new StringTokenizer(bInFile.readLine());

                    // Extract next attribute from file.
                    float attr = Float.valueOf(sToken.nextToken()).floatValue();
                    if (attr == noData)
                        attr = 0;
                    rasterMap.setAttribute(row,col,attr);
                }
            }
            
            // Close input file.            
       	    bInFile.close();
        }
        catch (FileNotFoundException e) {return null;}
        catch (IOException e) {return null;} 
        catch (NumberFormatException e) {return null;}	  
 
        return rasterMap;
    } 

    /** Attempts to read the given file representing an ascii vector map.
      * @param inFile File to read.
      * @return SpatialObject containing read file or null if not read.
      */
    private static SpatialObject readVectText(File inFile)
    {
        VectorMap vectorMap=new VectorMap();

        try
        {
            BufferedReader bInFile = new BufferedReader(new FileReader(inFile));
            StringTokenizer sToken;   // Reads in word at a time
        
            while (bInFile.ready())
            {
                int numCoords = 1;
                int type = SpatialModel.POINT;
                float x[],y[],attr;

    	        sToken = new StringTokenizer(bInFile.readLine());
                String word = sToken.nextToken().toUpperCase();

                if (word.startsWith("P"))
                {
                    x = new float[1];
                    y = new float[1];
                    x[0] = Float.valueOf(sToken.nextToken()).floatValue();
                    y[0] = Float.valueOf(sToken.nextToken()).floatValue();
                    attr = Float.valueOf(sToken.nextToken()).floatValue();
                    vectorMap.add(new GISVector(x,y,type,attr));
                    continue;                     
                }
                else if (word.startsWith("L"))
                {
                    numCoords = Integer.parseInt(sToken.nextToken());
                    type = SpatialModel.LINE;
                }
                else if (word.startsWith("A"))
                {
                    numCoords = Integer.parseInt(sToken.nextToken());
                    type = SpatialModel.AREA;
                }
                else continue;

                attr = Float.valueOf(sToken.nextToken()).floatValue();
                x = new float[numCoords];
                y = new float[numCoords];
                for (int i=0; i<numCoords; i++)
                {
                    sToken = new StringTokenizer(bInFile.readLine());
                    x[i] = Float.valueOf(sToken.nextToken()).floatValue();
                    y[i] = Float.valueOf(sToken.nextToken()).floatValue();
                }
                vectorMap.add(new GISVector(x,y,type,attr));
            }
        }
        catch (FileNotFoundException e) {return null;}
        catch (IOException e) {return null;} 
        catch (NumberFormatException e) {return null;}	

        return vectorMap;
    }   

    /** Attempts to read the given file representing an XML vector map.
      * @param inFile File to read.
      * @return SpatialObject containing read file or null if not read.
      */
    private static SpatialObject readXMLVect(File inFile)
    {
        VectorMap vectorMap=new VectorMap();

        XMLProcessor xmlPr = new XMLProcessor(inFile.getAbsolutePath());
        String coords[] = xmlPr.search("coordinates");
for (int i=0; i<coords.length; i++)
   System.out.println(coords[i]);
        return vectorMap;
    }

    /** Attempts to save the given spatial object as an XML file.
      * @param spObject Spatial object to save.
      * @param outFile File name to save.
      * @return true if saved correctly.
      */
    private static boolean writeXMLVect(SpatialObject spObject, File outFile)
    {
        // Only consider vector maps.
        if (!(spObject instanceof VectorMap))
            return false;

        // Create DOM out of VectorMap.


        return true;
    }
 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -