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

📄 miffile.java

📁 .mif .mid file read and write
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
                            protected void stringToValue()
                                throws Exception {
                                objValue = new Double(strValue);
                            }

                            protected void valueToString() {
                                // TODO use DecimalFormat class!!!
                                super.valueToString();
                            }
                        };
            } else if (atc == Float.class) {
                fieldValueSetters[i] = new MIFValueSetter("0") {
                            protected void stringToValue()
                                throws Exception {
                                objValue = new Float(strValue);
                            }

                            protected void valueToString() {
                                // TODO use DecimalFormat class!!!
                                super.valueToString();
                            }
                        };
            } else if (atc == Boolean.class) {
                fieldValueSetters[i] = new MIFValueSetter("false") {
                            protected void stringToValue()
                                throws Exception {
                                objValue = new Boolean("T".equalsIgnoreCase(
                                            strValue) ? "true"
                                                      : ("F".equalsIgnoreCase(
                                            strValue) ? "false" : strValue));
                            }

                            protected void valueToString() {
                                if ((objValue == null)
                                        || (((Boolean) objValue).booleanValue() == false)) {
                                    strValue = "F";
                                } else {
                                    strValue = "T";
                                }
                            }
                        };
            } else if (Date.class.isAssignableFrom( atc ) ) {
                // TODO Check conversion of date values - switch to java.sql.Date
                fieldValueSetters[i] = new MIFValueSetter("") {
                            protected SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "yyyyMMdd");

                            protected void stringToValue()
                                throws Exception {
                                if ((strValue != null) && !strValue.equals("")) {
                                    objValue = dateFormat.parse(strValue);
                                } else {
                                    objValue = null;
                                }

                                // Date.valueOf(strValue.substring(0, 4) + "-" + strValue.substring(4, 6) + "-" + strValue.substring(6));
                            }

                            protected void valueToString() {
                                if (objValue == null) {
                                    strValue = "";
                                } else {
                                    strValue = dateFormat.format(objValue);

                                    // strValue = ((Date) objValue).getYear() + "" + ((Date) objValue).getMonth() + "" + ((Date) objValue).getDay();
                                }
                            }
                        };
            } else if (atc == String.class) {
                fieldValueSetters[i] = new MIFValueSetter("") {
                            protected void stringToValue()
                                throws Exception {
                                objValue = new String(strValue);
                            }

                            // Quotes the string
                            protected void valueToString() {
                                strValue = new String("\""
                                        + objValue.toString().replaceAll("\"",
                                            "\"\"") + "\"");
                            }
                        };
            } else {
                throw new SchemaException("Unsupported attribute type: "
                    + atc.getName());
            }
        }

        return fieldValueSetters;
    }

    /**
     * Utility function for copying or moving files
     *
     * @param in Source file
     * @param out Destination file
     * @param deleteIn If true, source will be deleted upon successfull copy
     *
     * @throws IOException
     */
    protected static void copyFileAndDelete(File in, File out, boolean deleteIn)
        throws IOException {
        try {
            FileChannel sourceChannel = new FileInputStream(in).getChannel();
            FileChannel destinationChannel = new FileOutputStream(out)
                .getChannel();
            destinationChannel.transferFrom( sourceChannel, 0, sourceChannel.size() );
            if (deleteIn) {
                in.delete();
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    /**
     * <p>
     * Private  FeatureReader<SimpleFeatureType, SimpleFeature> inner class for reading Features from the MIF file
     * </p>
     */
    private class Reader implements  FeatureReader<SimpleFeatureType, SimpleFeature> {
        private MIFFileTokenizer mif = null;
        private MIFFileTokenizer mid = null;
        private boolean mifEOF = false;
        private String mifText = ""; // caption for text objects 
        private SimpleFeature inputFeature = null;
        private Object[] inputBuffer = null;
        private MIFValueSetter[] fieldValueSetters;

        private Reader(MIFFileTokenizer mifTokenizer,
            MIFFileTokenizer midTokenizer) throws IOException {
            inputBuffer = new Object[numAttribs];

            mif = mifTokenizer;
            mid = midTokenizer;

            // numAttribs == 0 when Reader is called from within readMifHeader for determining geometry Type
            if (numAttribs > 0) {
                try {
                    fieldValueSetters = getValueSetters();
                } catch (SchemaException e) {
                    throw new IOException(e.getMessage());
                }

                inputFeature = readFeature();
            }
        }

        public boolean hasNext() {
            return (inputFeature != null);
        }

        // Reads the next feature and returns the last one
        public SimpleFeature next() throws NoSuchElementException {
            if (inputFeature == null) {
                throw new NoSuchElementException("Reached the end of MIF file");
            }

            SimpleFeature temp = inputFeature;

            try {
                inputFeature = readFeature();
            } catch (Exception e) {
                throw new NoSuchElementException(
                    "Error retrieving next feature: " + e.toString());
            }

            return temp;
        }

        public SimpleFeatureType getFeatureType() {
            return featureType;
        }

        public void close() {
            try {
                if (mif != null) {
                    mif.close();
                }

                if (mid != null) {
                    mid.close();
                }
            } finally {
                mif = null;
                mid = null;
            }
        }

        protected void finalize() throws Throwable {
            close();
            super.finalize();
        }

        /**
         * Reads a single MIF Object (Point, Line, Region, etc.) as a Feature
         *
         * @return The feature, or null if the end of file was reached
         *
         * @throws IOException
         */
        private SimpleFeature readFeature() throws IOException {
            SimpleFeature feature = null;
            Geometry geom = readGeometry();

            if (mifEOF) {
                return null;
            }

            if (!mid.readLine()) {
                // TODO According to MapInfo spec., MID file is optional... in this case we should return the default values for the feature
                if (geom != null) {
                    throw new IOException("Unexpected end of MID file.");
                }

                return null;
            }

            // Reads data from mid file
            // Assumes that geomFieldIndex == 0
            try {
                String tok = "";
                int col = 0;

                while (!mid.isEmpty()) {
                    tok = mid.getToken(chDelimiter, false, true);

                    if (!fieldValueSetters[++col].setString(tok)) {
                        LOGGER.severe("Bad value:"
                            + fieldValueSetters[col].getError());
                    }

                    inputBuffer[col] = fieldValueSetters[col].getValue();
                }

                if (!mifText.equals("")) {
                    // MIF_TEXT MUST BE the LAST Field for now
                    inputBuffer[++col] = mifText;

                    // a better approach could be using a separate array of value setters for MIF_ fields
                    // (TEXT, ANGLE...)
                }

                if (col != (numAttribs - 1)) {
                    throw new Exception(
                        "Bad number of attributes read on MID row "
                        + mid.getLineNumber() + ": found " + col
                        + ", expecting " + numAttribs);
                }
            } catch (Exception e) {
                throw new IOException("Error reading MID file, line "
                    + mid.getLineNumber() + ": " + e.getMessage());
            }

            // Now add geometry and build the feature
            try {
                inputBuffer[0] = geom;
                feature = SimpleFeatureBuilder.build(featureType, inputBuffer, null);
            } catch (Exception e) {
                throw new IOException("Exception building feature: "
                    + e.getMessage());
            }

            return feature;
        }

        /**
         * Reads one geometric object from the MIF file
         *
         * @return The geometry object
         *
         * @throws IOException Error retrieving geometry from input MIF stream
         */
        private Geometry readGeometry() throws IOException {
            mifText = "";

            if (!mif.readLine()) {
                mifEOF = true;

                return null;
            }

            Geometry geom = null;

            try {
                // First of all reads geometry
                String objType = mif.getToken().toLowerCase();

                if (objType.equals(TYPE_NONE)) {
                    geom = null;
                } else if (objType.equals(TYPE_POINT)) {
                    geom = readPointObject();
                } else if (objType.equals(TYPE_LINE)) {
                    geom = readLineObject();
                } else if (objType.equals(TYPE_PLINE)) {
                    geom = readPLineObject();
                } else if (objType.equals(TYPE_REGION)) {
                    geom = readRegionObject();
                } else if (objType.equals(TYPE_TEXT)) {
                    geom = readTextObject();
                } else if (objType.equals(CLAUSE_PEN)
                        || objType.equals(CLAUSE_SYMBOL)
                        || objType.equals(CLAUSE_SMOOTH)
                        || objType.equals(CLAUSE_CENTER)
                        || objType.equals(CLAUSE_BRUSH)
                        || objType.equals(CLAUSE_FONT)
                        || objType.equals(CLAUSE_ANGLE)
                        || objType.equals(CLAUSE_JUSTIFY)
                        || objType.equals(CLAUSE_SPACING)
                        || objType.equals(CLAUSE_LABEL)) {
                    // Symply ignores styling clauses, so let's read the next lines
                    geom = readGeometry();
                } else {
                    // TODO add MultiPoint & Collection!!!
                    throw new IOException(
                        "Unknown or unsupported object in mif file:" + objType);
                }
            } catch (Exception e) {
                throw new IOException("File " + mifFile.getName() + ", line "
                    + mif.getLineNumber() + ": " + e.getMessage());
            }

            return geom;
        }

        /**
         * Reads Multi-Line (PLine) information from the MIF stream
         *
         * @return The (MULTI)LINESTRING object read
         *
         * @throws IOException Error retrieving geometry from input MIF stream
         */
        private Geometry readPLineObject() throws IOException {
            try {
                String tmp = mif.getToken(' ', true);
                int numsections = 1;
                int numpoints = 0;

                if (tmp.equalsIgnoreCase("MULTIPLE")) {
                    numsections = Integer.parseInt(mif.getToken(' ', true)); //read the number of sections
                    numpoints = Integer.parseInt(mif.getToken(' ', true)); //read the number of points
                } else {
                    // already got the number of points, simply parse it
                    numpoints = Integer.parseInt(tmp);
                }

                LineString[] lineStrings = new LineString[numsections];

                // Read each polyline
                for (int i = 0; i < lineStrings.length; i++) {
                    if (numpoints == 0) {
                        numpoints = Integer.parseInt(mif.getToken(' ', true));
                    }

                    Coordinate[] coords = new Coordinate[numpoints];

                    // Read each point
                    for (int p = 0; p < coords.length; p++) {

⌨️ 快捷键说明

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