java判断文本文件编码格式juniversalchardet使用

识别文件编码类型,使用juniversalchardet,内含juniversalchardet-1.0.3.jar 识别文件编码类型,使用juniversalchardet,内含juniversalchardet-1.0.3.jar 常见编码识别 UTF-8,GBK,UTF-16,GB2312 等等 还有不常见的EUC-TW Cyrillic MACCYRILLIC等 一共支持已测试的36种编码 立即下载

java判断文本文件编码格式juniversalchardet使用

今天项目经理让写一个判断文本文件格式的接口,废话不多说直接上代码。

juniversalchardet官网地址: http:code.google.com/p/juniversalchardet/

github地址 https://github.com/thkoch2001/juniversalchardet
支持的编码格式
- Chinese

  • ISO-2022-CN

  • BIG-5

  • EUC-TW

  • GB18030

  • HZ-GB-2312

  • Cyrillic

    • ISO-8859-5
    • KOI8-R
    • WINDOWS-1251
    • MACCYRILLIC
    • IBM866
    • IBM855
  • Greek

    • ISO-8859-7
    • WINDOWS-1253
  • Hebrew

    • ISO-8859-8
    • WINDOWS-1255
  • Japanese

    • ISO-2022-JP
    • Shift_JIS
    • EUC-JP
  • Korean

    • ISO-2022-KR
    • EUC-KR
  • Unicode

    • UTF-8
    • UTF-16BE / UTF-16LE
    • UTF-32BE / UTF-32LE / X-ISO-10646-UCS-4-3412 / X-ISO-10646-UCS-4-2143
  • Others

    • WINDOWS-1252

实践

pom.xml文件

	<dependency>
		<groupId>com.googlecode.juniversalchardet</groupId>
		<artifactId>juniversalchardet</artifactId>
		<version>1.0.3</version>
	</dependency>

java代码

@RequestMapping("/resultCode")
    public Map<String,String> resultCode(@RequestParam("file") MultipartFile file){
        Map<String,String> map = new HashMap<>();
        /**
		*获取文件类型        
		*/
        String fileType = file.getContentType();
            try {
            	/**
            	*判断文件类型
            	*如.text/.sql/.xls/.xlxs等;
            	*/
                if(fileType.contains("text") || fileType.contains("sql")||fileType.contains("excel")||fileType.contains("openxmlformats-officedocument.spreadsheetml.sheet")){
                    byte[] buf = new byte[4096];
                    InputStream fis = file.getInputStream();
                    // (1)
                    UniversalDetector detector = new UniversalDetector(null);

                    // (2)
                    int nread;
                    while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
                        detector.handleData(buf, 0, nread);
                    }
                    // (3)
                    detector.dataEnd();

                    // (4)
                    String encoding = detector.getDetectedCharset();
                    if (encoding != null) {
                        map.put("encoding",encoding);
                    } else {
                        map.put("error","No encoding detected.");
                    }

                    // (5)
                    detector.reset();

                    map.put("code","0");
                    map.put("msg","成功!");
                }else{
                    map.put("error","请上传SQL/TEXT/xls/xlsx格式文件!");
                }
            }catch (Exception e){
                map.put("code","-1");
                map.put("msg","失败!");
            }
        return map;
    }

然后就可以直接调用接口测试。

juniversalchardet-2.0.0.jar juniversalchardet-2.0.0.jar是mozilla公司推出的用来识别文件内容字符集的jar包,特点是快速、准确、实用 立即下载

相关推荐

juniversalchardet-1.0.3-API文档-中文版.zip

赠送jar包:juniversalchardet-1.0.3.jar; 赠送原API文档:juniversalchardet-1.0.3-javadoc.jar; 赠送源代码:juniversalchardet-1.0.3-sources.jar; 赠送Maven依赖信息文件:juniversalchardet-1.0.3.pom; 包含翻译后的API文档:juniversalchardet-1.0.3-javadoc-API文档-中文(简体)版.zip; Maven坐标:com.googlecode.juniversalchardet:juniversalchardet:1.0.3; 标签:googlecode、juniversalchardet、中文文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用。

测试文件编码工具类juniversalchardet,java读取csv文件中文乱码

前言: java读取csv文件中文乱码,文件编码不对。究其原因, 文件被转换过,重新写入指定编码不对, 还有就是读取csv时候指定的编码不对。 导出csv文件,excel和wps打开显示不对,要导出指定编码GBK或者GB2312 我们如何获取编码呢?下面就是如何获取原文件的编码。 读取csv时候我们用windows创建的csv文件,解析出是WINDOWS-1252,我们解析传入的就是GB...

haoweng4800的博客 1683

juniversalchardet-1.0.3-API文档-中英对照版.zip

赠送jar包:juniversalchardet-1.0.3.jar; 赠送原API文档:juniversalchardet-1.0.3-javadoc.jar; 赠送源代码:juniversalchardet-1.0.3-sources.jar; 赠送Maven依赖信息文件:juniversalchardet-1.0.3.pom; 包含翻译后的API文档:juniversalchardet-1.0.3-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:com.googlecode.juniversalchardet:juniversalchardet:1.0.3; 标签:googlecode、juniversalchardet、中英对照文档、jar包、java; 使用方法:解压翻译后的API文档,用浏览器打开“index.html”文件,即可纵览文档内容。 人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用。 双语对照,边学技术、边学英语。

Java判断文本文件编码的有用工具:juniversalchardet

字符集检测工具类:CharsetDetectUtil.java。文件工具类FileUtils.java。

tttzzzqqq2018的博客 1091

如何用ggplot2绘制专业级双侧柱状图展示GO富集结果(附完整代码)

本文详细介绍了如何使用R语言的ggplot2包绘制专业级双侧柱状图展示GO富集结果,包括数据预处理、基础图形构建、高级样式定制和出版级细节调整。通过完整的代码示例和实用技巧,帮助生物信息学研究人员高效可视化高通量数据,提升学术图表的质量和可读性。

weixin_30342209的博客 77

直线电机驱动技术原理与应用解析

直线电机作为直接电能-直线运动转换装置,其核心原理基于电磁感应定律和洛伦兹力公式。通过三相交流电在定子绕组中产生行波磁场,与动子永磁体相互作用实现精准推力控制。相比传统旋转电机传动系统,直线电机具有零传动间隙、高动态响应(加速度可达10g)和微米级定位精度等技术优势,这使其成为半导体光刻机、精密数控机床等高端装备的关键驱动部件。现代直线电机驱动单元通常采用三环控制架构(电流环、速度环、位置环),配合SiC功率器件和高分辨率光栅反馈,实现纳米级运动控制。随着模块化设计和直接冷却技术的发展,直线电机正朝着更高功

weixin_26802933的博客 260

java判断文本文件编码格式

上篇文章需要读取当前java或者配置文件的编码格式,这里主要支持UTF-8、GBK、UTF-16、Unicode等 /** * 判断文件的编码格式 * @param fileName :file * @return 文件编码格式 * @throws Exception */ public static String codeString(File fileName) thro...

lipeng的博客 1万+

在pycharm2021.2中学习opencv图像处理,基于python3.9.7、pycharm完成配置

在pycharm中学习opencv图像处理安装python下载python安装包开始安装安装pycharm社区版下载pycharm开始安装如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 安装python 使用pycharm学习opencv应该是最简单的了,对新手比较友好,

steveqobs 7710

java 通过 InputStream 判断文件编码格式

java 通过 InputStream 判断文件编码格式

AKA石头 2733

ORACLE 12C RAC 启动报错,错误代码 ORA-27300,ORA-27301,ORA-27302

非一体机,12.2 无任何补丁,2套X86服务器,1节点集群异常(数据库正常,还有会话),2节点正常工作,负载不高,硬件、空间均未检查到异常,多路径存在掉线的情况,但通过Mulitpath -ll 看又是正常的,2根私有网络,其中一根不同,sysctl中配置的稀疏模式。5、再次加成crs alert ohas等集群日志,以及根据现象和错误再次到后台sr中查找可用信息,发现有一个类似问题,12.2 RAC 无任何补丁,报同样错误,解决方案为重启两套服务器。查询MOS文档以及后台文档,排除上面指出的问题。

weixin_42344665的博客 1465

点云目标检测:open3d多窗口联动可视化

多个模型之间的对比除了指标之外,还需要可以直接直观的对比可视化结果,这次介绍一下如何使用open3d同时打开两个窗口分别加载两个模型的结果进行对比,同时实现两个窗口的联动,也就是当一个窗口拖动或者缩放时另外一个窗口也跟着做同样的变换。

zhaoguanhua的博客 4688

校验文件的编码格式-谷歌juniversalchardet

Java 文件编码格式检查

yanxilu的博客 602

《MATLAB项目实战》,专栏目录和介绍

MATLAB 是一款强大且广泛应用的数值计算和数据可视化软件工具,它提供了一个高效、简洁的编程环境,使用户能够进行从简单的矩阵运算到复杂的多维数据分析的各种计算任务。无论是在人工智能、计算机视觉、图像处理还是其他领域,MATLAB 都能够提供精准、快速的解决方案,因此成为了全球科研人员、工程师以及数据分析师的得力工具。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 6478

java获得文件编码格式

java在读取文件时容易出现乱码,究其原因是读取文件的编码跟文件本身的编码不一致,那在解析文件前如何获取文件的编码格式呢?本文主要通过google开源的 juniversalchardet 来实现。 首先在项目中引入jar包 <dependency> <groupId>com.googlecode.juniversalchardet&...

xiao1122的专栏 1095

eCognition易康操作教程(二):多尺度分割基于多光谱数据构建规则集,结合DSM高程数据提取建筑物、树木和绿地

一、数据 数据来源:教程中的实验数据,共包含RGB三个波段,还有数字地表模型(以下简称DSM)文件。 图一 RGB影像 数据特征:数据范围较小,要素种类少,仅包含较多的建筑和大片的绿地。由于建筑的房顶使用的材料和材料颜色不同,所以建筑的光谱特征没有规律,是不连续的特征。而绿地的光谱特征则十分容易分辨。 但是建筑通常具有规则的形状,而且建筑相比于周围其他要素...

蒹葭苍苍 8305

【OpenClaw从入门到精通】:Web控制台使用全解析——可视化配置与监控(2026实操版)

在OpenClaw的多种管理方式中,Web控制台提供了最直观、最友好的用户体验。通过图形化界面,用户可以轻松完成复杂的配置任务,实时监控系统状态,以及进行各种管理操作。对于不熟悉命令行的用户来说,Web控制台是最佳选择。

一键难忘的博客 1930

Android--判断文本文件编码

以后再也不用为读取文件乱码而烦恼啦!

爱自在的专栏 5042

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Java上传csv文件检测编码格式,传入参数MultipartFile file,返回文件编码格式

Java上传csv文件检测编码格式,传入参数MultipartFile file,返回文件编码格式。

tpl9236 的博客 997

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java 判断byte(数据库blob)的编码格式

1、首先添加依赖 <dependency> <groupId>com.googlecode.juniversalchardet</groupId> <artifactId>juniversalchardet</artifactId> <version>1.0.3</version> </dependency> 2、案例操作

wuesr的博客 1561

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

Android--推断文本文件编码

方法1:利用windows文本文件编码特点。 windows下。Unicode、Unicode big endian和UTF-8编码的txt文件的开头会多出几个字节,各自是FF、FE(Unicode),FE、FF(Unicode big endian),EF、BB、BF(UTF-8)。 public static String getCharset...

weixin_30824479的博客 172

java怎么判断byte[]的原字符串的编码?

一个byte数组,byte[] buf,是由一个字符串转换来的,如何判断字符串使用的是什么编码? Mozilla的一个组件提供了相应功能: 组件叫,juniversalchardet,下载地址:https://juniversalchardet.googlecode.com/files/juniversalchardet-1.0.3.jar 也可以到组件官网下载最新版本:https://co

AJAXHu的专栏 9390

java实现 批量转换文件编码格式

java实现 批量转换文件编码格式 转载自https://www.cnblogs.com/enenen/p/10761362.html 在原有基础上增加了原始编码识别,跳过已经是目标编码格式的文件。只需要传文件夹的绝对路径,目标编码格式,需要转换的文件扩展名三个参数就可以了 需要的依赖 <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all

qq_44190799的博客 549

JAVA文本文件编码获取

JAVA文本文件编码获取。

小马的博客 425

android获取文本编码

android获取文本编码)

楠之枫雪的博客 1280

检测编码工具juniversalchardet

// java.io.FileInputStream fis = null; // try { // fis = new java.io.FileInputStream(fileName); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // (1)

hfy779012303的专栏 186
下一篇: formData上传多文件,并用Blob将数据生成文件。
Hello_Tree__
博客等级 码龄8年 3粉丝 14原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值