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

📄 filetools.java

📁 基于MPEG 7 标准,符合未来语义网架构,很值得参考
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
        String returnValue = res.getBaseDir();
        return returnValue;
    }

    /**
     * search for all occurrencies of a String and replace it with an other String
     * input:
     * str1: source-String that will be processed
     * old1: string, that is search in str1
     * new1: old1 will be replaced by new1
     */
    public static String replace(String str1, String old1, String new1) {
        String str = str1;
        String oldStr = old1;
        String newStr = new1;

        if ((str == null) || (oldStr == null) || (newStr == null) ||
                (str.length() == 0) || (oldStr.length() == 0)) {
            return str1;
        }

        String result = "";

        int i = 0;
        while (i <= (str.length() - oldStr.length())) {
            String sub = str.substring(i, i + oldStr.length()); // part of the text-string
            if (sub.equals(oldStr)) {
                result += newStr;
                i += oldStr.length();
            } else {
                result += str.substring(i, ++i);
            }
        }  // end for
        // add the rest on the end if not already replaced;
        if (i <= str.length()) {
            result += str.substring(i, str.length());
        }


        return result;
    }  // end method


    /**
     * Converts "\temp\sample.txt" -> "file:///temp/sample.txt"
     */
    public static String setUrlPrefix(java.lang.String fileName1) {
        String returnValue = fileName1;
        if (fileName1 == null)
            return "file:/";

        if ((!fileName1.startsWith("file:")) &&
                (!fileName1.startsWith("http:")) &&
                (!fileName1.startsWith("jar:")) &&
                (!fileName1.startsWith("rmi:")) &&
                (!fileName1.startsWith("https:")) &&
                (!fileName1.startsWith("ftp:"))) {
            File file = new File(fileName1);
            returnValue = "file:/" + file.getAbsolutePath();
        }

        return returnValue;
    }

    /**
     * remove "file:" url prefix for file-urls. It is mainly used to get a valid path for
     * new File(myPath);
     */
    public static String removeFileUrlPrefix(java.lang.String fileName1) {
        String returnValue = fileName1;

        try {
            if (fileName1 == null) {
                return "";
            }


            //URI uri = new URI(fileName1);
            //returnValue = uri.getPath();  //get the filename and decode octed strings

            if (fileName1.startsWith("file:")) {

                // somethimes a file uri string is not encoded int the right way
                fileName1 = replace(fileName1, "[", "%5B");
                fileName1 = replace(fileName1, "]", "%5D");
                fileName1 = replace(fileName1, " ", "%20");

                String path = new URI(fileName1).getPath(); // path contains spaces, ...
                //String path = new URI(fileName1).toString();  //toString contains %20 ...
                // on a dos filename remove the leading slash. "/c:/temp" -> "c:/temp"
                if ((path.length() >= 2) && (path.charAt(2) == ':')) {
                    returnValue = path.substring(1);
                } else {
                    returnValue = path;
                }
            }

            /*
            if (fileName1.startsWith("file:///")) {
                returnValue = convertString(fileName1, 8);
            } else
            if (fileName1.startsWith("file://")) {
                returnValue = convertString(fileName1, 7);
            } else
            if (fileName1.startsWith("file:/")) {
                returnValue = convertString(fileName1, 6);
            } else
            if (fileName1.startsWith("file:")) {
                returnValue = convertString(fileName1, 5);
            }
            */
        } catch (Exception e) {
            System.out.println("file: " + fileName1);
            e.printStackTrace();
        }

        return returnValue;
    }

    private static String convertString(String url, int startPos) {
        String returnValue = url.substring(startPos);
        returnValue = returnValue.replaceAll("%20", " ");

        return returnValue;
    }

    /**
     * remove url prefix"jar:file:/"
     * example: "jar:file:/D:/tools"  -> "D:/tools"
     */
    public static String removeUrlPrefixes(java.lang.String fileName1) {
        String returnValue = fileName1;
        if (fileName1 == null)
            return "";

        //log.debug(" U input: " + returnValue);
        if (fileName1.startsWith("jar:file:")) {
            returnValue = fileName1.substring(9);
        }

        //log.debug(" U <jar:file:> : " + returnValue);

        // on windows systems remove the remaining "/x:"
        if (fileName1.charAt(2) == ':') {
            returnValue = fileName1.substring(3);
        }

        //log.debug(" U </X:> : " + returnValue);

        return returnValue;
    }


    public static boolean hasUrlPrefix(java.lang.String fileName1) {
        if (fileName1 == null)
            return false;

        String filenName = fileName1;
        return (setUrlPrefix(fileName1).equalsIgnoreCase(filenName));
    }

    /**
     * Read the content of a File and store it in a String
     */
    public static String readFromFile(String filename1, String default1, String l_locale) {
        String ret = "";
        if (l_locale == null || l_locale.equals("")) l_locale = "UTF-8";

        //log.debug("try reading: " + filename1);
        try {
            //BufferedReader inputStream = new BufferedReader(new FileReader(filename1));
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(filename1), l_locale));

            StringBuffer strBuff = new StringBuffer();
            while (inputStream.ready()) {
                String input = inputStream.readLine();
                if ((input != null)) {
                    input = input.trim();
                    strBuff.append(input + FileTools.LINE_BREAK);
                } // end if
            } // end while

            ret = strBuff.toString();

            if ((ret == null) || (ret.length() == 0)) {
                ret = default1;
            }
        } catch (Exception e) {
            //log.debug(e);
            ret = default1;
        }

        return ret;
    } // end method

    public static String readFromFile(String filename1, String default1) {
        return readFromFile(filename1, default1, null);
    }

    public static String readFromFileUtf8(String filename1, String default1) {
        return readFromFile(filename1, default1, "UTF-8");
    }

    public static String readFromStream(InputStream a_stream) {
        String returnValue = null;

        try {
            char buf[] = new char[BUFFER_SIZE];
            InputStreamReader reader = new InputStreamReader(a_stream); //TODO: , encoding);
            StringBuffer strBuff = new StringBuffer();
            while (reader.ready()) {
                String input;

                int availableBytes = reader.read(buf);
                input = new String(buf, 0, availableBytes);
                if ((input != null)) {
                    input = input.trim();
                    strBuff.append(input + FileTools.LINE_BREAK);
                } // end if
            }

            returnValue = strBuff.toString();
        } catch (IOException e) {
            //log.error(e);
            e.printStackTrace();
        }

        return returnValue;
    }


    /**
     * read key-value pairs form a file. A line in the file looks like "key=value"
     *
     * @param fileName
     * @return
     */
    public static Map readMapFromFile(String fileName) {
        Map m = new HashMap();
        try {
            BufferedReader inputStream = new BufferedReader(new FileReader(fileName));
            while (inputStream.ready()) {
                //get next key2-value pair from file
                String input = inputStream.readLine();
                if ((input != null) && (input.length() > 0)) {
                    input = input.trim();
                    String key = input.substring(0, input.indexOf("="));
                    String value = input.substring(input.indexOf("=") + 1, input.length());
                    m.put(key, value);
                }
            }
            inputStream.close();
            //Log.notice("Map loaded from file <" + fileName + ">");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return m;
    }


    /**
     * reads every line from fileName and assignes each line to a HashSet. The
     * created HashSEt is returned
     *
     * @param fileName
     * @param l_locale a locale character setting (e.g. UTF-8). If ommitted UTF-8 is assumed
     * @return
     */
    public static Set readSetFromFile(String fileName,
                                      String l_locale) throws IOException {
        Set m = new HashSet();
        if (l_locale == null || l_locale.equals("")) l_locale = "UTF-8";

        BufferedReader inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), l_locale));
        String l_line;
        while ((l_line = inputStream.readLine()) != null) {
            m.add(l_line.trim());
        }
        inputStream.close();
        //Log.notice("Map loaded from file <" + fileName + ">");
        return m;
    }

    /**
     * reads every line from fileName. Each line is splitted using string.split(l_string_split_filter)
     * and assignes each token to a HashSet. Null or empty strings are not assigned if l_keep_empty is false The
     * created HashSEt is returned
     *
     * @param fileName
     * @param l_locale a locale character setting (e.g. UTF-8). If ommitted UTF-8 is assumed
     * @return
     */
    public static Set readSetFromFileAndBreakUpLines(String fileName,
                                                     String l_locale,
                                                     String l_string_split_filter,
                                                     boolean l_keep_empty) throws IOException {
        Set m = new HashSet();
        if (l_locale == null || l_locale.equals("")) l_locale = "UTF-8";

        BufferedReader inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), l_locale));
        String l_line;
        while ((l_line = inputStream.readLine()) != null) {
            String[] tokens = l_line.trim().split(l_string_split_filter);
            for (int i = 0; i < tokens.length; i++) {
                if (l_keep_empty || !tokens[i].equals(""))
                    m.add(tokens[i]);


            }
        }
        inputStream.close();
        //Log.notice("Map loaded from file <" + fileName + ">");
        return m;
    }

    /**
     * read single line of a file and store each line in a separate list-entry
     *
     * @param fileName
     * @return
     */
    public static List readLinesFromFile(String fileName) {
        List returnValue = new ArrayList();
        try {
            BufferedReader inputStream = new BufferedReader(new FileReader(fileName));
            while (inputStream.ready()) {
                //get next key2-value pair from file
                String input = inputStream.readLine();
                if ((input != null) && (input.length() > 0)) {
                    input = input.trim();

                    returnValue.add(input);
                }
            }
            inputStream.close();
            //Log.notice("Map loaded from file <" + fileName + ">");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnValue;
    }

    public static List<String> readLinesFromStream(InputStream a_stream) {
        List<String> returnValue = new ArrayList<String>();

        try {
            char buf[] = new char[BUFFER_SIZE];
            InputStreamReader inr = new InputStreamReader(a_stream); //TODO: , encoding);
            BufferedReader reader = new BufferedReader(inr);
            StringBuffer strBuff = new StringBuffer();
            while (reader.ready()) {
                String input;

                input = reader.readLine();
                if ((input != null)) {
                    input = input.trim();
                    returnValue.add(input);
                } // end if
            }
        } catch (IOException e) {
            //log.error(e);
            e.printStackTrace();
        }

        return returnValue;
    }


    // simple method that saves the given string to the given filename
    // any existing files are replaced
    public static void saveToFile(String fname, String data) {
        try {
            makeDirectory(fname);
            FileOutputStream fout = new FileOutputStream(fname);
            OutputStreamWriter stream_out = new OutputStreamWriter(fout);
            stream_out.write(data);
            stream_out.flush();
            stream_out.close();
        } catch (Exception e) {
            //log.error(e);
        }
    }

    // simple method that saves the given string to the given filename
    // any existing files are replaced
    public static void saveToFile(String fname, String data, boolean append) {
        try {
            if (!append) {
                saveToFile(fname, data);
            } else {
                if (!existsFile(fname)) {
                    saveToFile(fname, data);
                } else {
                    FileOutputStream fout = new FileOutputStream(fname, true);
                    OutputStreamWriter stream_out = new OutputStreamWriter(fout);
                    stream_out.write("\n");
                    stream_out.write(data);
                    stream_out.flush();
                    stream_out.close();
                }
            }
        } catch (Exception e) {
            //log.error(e);
        }
    }

    /**
     * simple method that saves the given byteArray to the given filename
     * any existing files are replaced
     */
    public static void saveToFile(String fname, byte[] data) {
        try {
            makeDirectory(fname);
            FileOutputStream fout = new FileOutputStream(fname);
            DataOutputStream streamOut = new DataOutputStream(fout);
            //ByteArrayOutputStream byteOut = new ByteArrayOutputStream(fout);

            streamOut.write(data);
            streamOut.flush();
            streamOut.close();
        } catch (Exception e) {
            //log.error(e);
        }
    }

    /**
     * simple method that saves the given inputStrream to the given filename
     * any existing files are replaced
     */
    public static void saveToFile(String fname, InputStream inputStream) {
        try {
            makeDirectory(fname);
            if (inputStream != null) {
                FileOutputStream fout = new FileOutputStream(fname);
                DataOutputStream streamOut = new DataOutputStream(fout);

⌨️ 快捷键说明

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