繁体   English   中英

从Java中的String对象中检测文件类型(json,html,text)

[英]Detect file type (json, html, text) from a String object in Java

我的Java类将接收一个String对象,该对象可以是json,html或纯文本。 我需要能够从Java String对象中检测哪种类型。

Apache Tika执行此操作,但仅检测File对象中的类型。 当我传递一个String对象时,它返回“application / octet-stream”作为类型(对于所有类型),这是不正确的。

到目前为止,我们只需要检测String是html还是纯文本。 在提供的代码示例中,我们只需要搜索明显的html标记。 现在,我们需要扫描String并确定它是html,json还是纯文本。

如果存在可以从String对象中检测到类型的第三方库,我很乐意使用它。

public static final String[] HTML_STARTS = {
    "<html>",
    "<!--",
    "<!DOCTYPE",
    "<?xml",
    "<body"
};
public static boolean isJSON(String str)
{
    str = str.trim();
    if(str[0] == '{' && str[str.length-1] == '}') {
        return true;
    }

    return false;
}


public static boolean isHTML(String str)
{
    List<String> htmlTags = Arrays.asList(
                                "<html>",
                                "<!--",
                                "<!DOCTYPE",
                                "<?xml",
                                "<body"
                            );

    return htmlTags.stream().anyMatch(string::contains);
}

public static int IS_PLAIN = 0;
public static int IS_HTML = 1;
public static int IS_JSON = 2;

public static int getType(String str)
{
    if(isJSON(str)) return IS_JSON;
    else if(isHTML(str)) return IS_HTML;
    else return IS_PLAIN;
}

您可以使用JSoup来解析HTML,使用Jackson或Gson来解析JSON。

如何返回带有“

[英]How to return an ID with an '<input type='text' string from Java using JSON and AJAX to HTML

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM