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

📄 miffile.java

📁 .mif .mid file read and write
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
                        PrecisionModel.FLOATING), SRID.intValue());
        }

        geometryName = (String) getParam(MIFDataStore.PARAM_GEOMNAME,
                "the_geom", false, params);
        fieldNameCase = ((String) getParam(MIFDataStore.PARAM_FIELDCASE, "",
                false, params)).toLowerCase();

        geometryClass = ((String) getParam(MIFDataStore.PARAM_GEOMTYPE,
                "untyped", false, params)).toLowerCase();

        namespace = (URI) getParam("namespace", FeatureTypes.DEFAULT_NAMESPACE, false,
                params);
    }

    /**
     * Returns a parameter value from the parameters map
     *
     * @param name
     * @param defa
     * @param required
     * @param params
     *
     *
     * @throws IOException if required parameter is missing
     */
    private Object getParam(String name, Object defa, boolean required,
        Map params) throws IOException {
        Object result;

        try {
            result = params.get(name);
        } catch (Exception e) {
            result = null;
        }

        if (result == null) {
            if (required) {
                throw new IOException("MIFFile: parameter " + name
                    + " is required");
            }

            result = defa;
        }

        return result;
    }

    /**
     * <p>
     * Sets the value for a Header Clause. Possible values are:
     * </p>
     * 
     * <ul>
     * <li>
     * MIFDataStore.HCLAUSE_VERSION = Version number ("310")
     * </li>
     * <li>
     * MIFDataStore.HCLAUSE_CHARSET = Charset name ("WindowsLatin1")
     * </li>
     * <li>
     * MIFDataStore.HCLAUSE_UNIQUE = Comma-separated list of field indexes
     * (1..numFields) corresponding to unique values (i.e. street names for
     * street segments)
     * </li>
     * <li>
     * MIFDataStore.HCLAUSE_INDEX = Comma-separated list of field indexes
     * (1..numFields) indicating which fields have to be indexed in MapInfo
     * </li>
     * <li>
     * MIFDataStore.HCLAUSE_COORDSYS = MapInfo CoordSys clause
     * </li>
     * <li>
     * MIFDataStore.HCLAUSE_TRANSFORM = Comma-separated list of four
     * transformation parameters ("1000, 1000, 0, 0")
     * </li>
     * </ul>
     * 
     *
     * @param clause Name of the Header Clause
     * @param value Value for the Header Clause
     *
     * @throws IOException Bad delimiter was specified
     */
    private void setHeaderClause(String clause, String value)
        throws IOException {
        if (value == null) {
            value = "";
        }

        if (clause.equals(MIFDataStore.HCLAUSE_DELIMITER)
                && (value.equals("") || value.equals("\""))) {
            throw new IOException("Bad delimiter specified");
        }

        header.put(clause, value);
    }

    /**
     * Gets the value for an header clause
     *
     * @param clause
     *
     */
    public String getHeaderClause(String clause) {
        try {
            return (String) getParam(clause, "", false, header);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * <p>
     * Opens the MIF file for input and returns a  FeatureReader<SimpleFeatureType, SimpleFeature> for accessing
     * the features.
     * </p>
     * 
     * <p>
     * TODO Concurrent file access is still not handled. MUST LOCK FILE and
     * return an error if another  FeatureReader<SimpleFeatureType, SimpleFeature> is open - Handle concurrent
     * access with synchronized(mif) / or Filesystem locking is enough?
     * </p>
     *
     * @return A  FeatureReader<SimpleFeatureType, SimpleFeature> for reading features from MIF/MID file
     *
     * @throws IOException
     */
    public  FeatureReader<SimpleFeatureType, SimpleFeature> getFeatureReader() throws IOException {
        MIFFileTokenizer mifTokenizer = null;
        MIFFileTokenizer midTokenizer = null;

        // if exists outMIF throw new IOException("File is being accessed in write mode");
        try {
            mifTokenizer = new MIFFileTokenizer(new BufferedReader(
                        new FileReader(mifFile)));
            midTokenizer = new MIFFileTokenizer(new BufferedReader(
                        new FileReader(midFile)));
            readMifHeader(true, mifTokenizer); // skips header

            return new Reader(mifTokenizer, midTokenizer);
        } catch (Exception e) {
            if (mifTokenizer != null) {
                mifTokenizer.close();
            }

            if (midTokenizer != null) {
                midTokenizer.close();
            }

            throw new IOException("Error initializing reader: " + e.toString());
        }
    }

    /**
     * Returns a FeatureWriter for writing features to the MIF/MID file.
     *
     * @return A featureWriter for this file
     *
     * @throws IOException
     */
    public FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriter() throws IOException {
        return getFeatureWriter(false);
    }

    /**
     * <p>
     * Private FeatureWriter in append mode, could be called by
     * DataStore.getFeatureWriterAppend(); not implemented yet
     * </p>
     *
     * @param append
     *
     *
     * @throws IOException
     */
    private FeatureWriter<SimpleFeatureType, SimpleFeature> getFeatureWriter(boolean append)
        throws IOException {
        if (append) {
            // copy inMif to OutMIf
        } else {
            // WriteHeader
        }

        PrintStream outMif = new PrintStream(new FileOutputStream(mifFileOut,
                    append));
        PrintStream outMid = new PrintStream(new FileOutputStream(midFileOut,
                    append));

        return new Writer(outMif, outMid, append);
    }

    /**
     * Creates the MIF file header
     *
     * @return the Header as a String
     *
     * @throws SchemaException A required header clause is missing.
     */
    private String exportHeader() throws SchemaException {
        // Header tags passed in parameters are overridden by the tags read from mif file 
        String header = exportClause(MIFDataStore.HCLAUSE_VERSION, true, false)
            + exportClause(MIFDataStore.HCLAUSE_CHARSET, true, true) // TODO Charset clause support should imply character conversion????
            + exportClause(MIFDataStore.HCLAUSE_DELIMITER, true, true)
            + exportClause(MIFDataStore.HCLAUSE_UNIQUE, false, false)
            + exportClause(MIFDataStore.HCLAUSE_INDEX, false, false)
            + exportClause(MIFDataStore.HCLAUSE_COORDSYS, false, false)
            + exportClause(MIFDataStore.HCLAUSE_TRANSFORM, false, false);

        header += ("Columns " + (numAttribs - 1) + "\n");

        for (int i = 1; i < numAttribs; i++) {
            AttributeDescriptor at = featureType.getAttribute(i);
            header += ("  " + at.getLocalName() + " " + getMapInfoAttrType(at)
            + "\n");
        }

        header += "Data\n";

        return header;
    }

    private String exportClause(String clause, boolean required, boolean quote)
        throws SchemaException {
        String result = getHeaderClause(clause);

        if (!result.equals("")) {
            if (quote) {
                result = MIFStringTokenizer.strQuote(result);
            }

            return clause + " " + result + "\n";
        }

        if (required) {
            throw new SchemaException("Header clause " + clause
                + " is required.");
        }

        return "";
    }

    /**
     * Maps an AttributeType to a MapInfo field type
     *
     * @param at Attribute Type
     *
     * @return the String description of the MapInfo Type
     */
    private String getMapInfoAttrType(AttributeDescriptor at) {
        if (at.getType().getBinding() == String.class) {
        	
            int l = AttributeTypes.getFieldLength(at, MAX_STRING_LEN);

            if (l <= 0) {
                l = MAX_STRING_LEN;
            }

            return "Char(" + l + ")";
        } else if (at.getType().getBinding() == Integer.class) {
            return "Integer";
        } else if ((at.getType().getBinding() == Double.class)
                || (at.getType().getBinding() == Float.class)) {
            return "Float";
        } else if (at.getType().getBinding() == Boolean.class) {
            return "Logical";
        } else if (at.getType().getBinding() == Date.class) {
            return "Date";
        } else {
            return "Char(" + MAX_STRING_LEN + ")"; // TODO Should it raise an exception here (UnsupportedSchema) ?
        }
    }

    /**
     * Sets the path name of the MIF and MID files
     *
     * @param path The full path of the .mif file, with or without extension
     * @param mustExist True if opening file for reading
     *
     * @throws FileNotFoundException
     */
    private void initFiles(String path, boolean mustExist)
        throws FileNotFoundException {
        File file = new File(path);

        if (file.isDirectory()) {
            throw new FileNotFoundException(path + " is a directory");
        }

        String fName = getMifName(file.getName());
        file = file.getParentFile();

        mifFile = getFileHandler(file, fName, ".mif", mustExist);
        midFile = getFileHandler(file, fName, ".mid", mustExist);

        mifFileOut = getFileHandler(file, fName, ".mif.out", false);
        midFileOut = getFileHandler(file, fName, ".mid.out", false);
    }

    /**
     * Returns the name of a .mif file without extension
     *
     * @param fName The file name, possibly with .mif extension
     *
     * @return The name with no extension
     *
     * @throws FileNotFoundException if extension was other than "mif"
     */
    protected static String getMifName(String fName)
        throws FileNotFoundException {
        int ext = fName.lastIndexOf(".");

        if (ext > 0) {
            String theExt = fName.substring(ext + 1).toLowerCase();

            if (!(theExt.equals("mif"))) {
                throw new FileNotFoundException(
                    "Please specify a .mif file extension.");
            }

            fName = fName.substring(0, ext);
        }

        return fName;
    }

    /**
     * Utility function for initFiles - returns a File given a parent path, the
     * file name without extension and the extension Tests different extension
     * case for case-sensitive filesystems
     *
     * @param path Directory containing the file
     * @param fileName Name of the file with no extension
     * @param ext extension with trailing "."
     * @param mustExist If true, raises an excaption if the file does not exist
     *
     * @return The File object
     *
     * @throws FileNotFoundException
     */
    protected static File getFileHandler(File path, String fileName,
        String ext, boolean mustExist) throws FileNotFoundException {
        File file = new File(path, fileName + ext);

        if (file.exists() || !mustExist) {
            return file;
        }

        file = new File(path, fileName + ext.toUpperCase());

        if (file.exists()) {
            return file;
        }

        throw new FileNotFoundException("Can't find file: " + file.getName());
    }

    /**

⌨️ 快捷键说明

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