Как определить кодировку текстового файла
Кодировкой текста в файлах цифровых документов называют способ сопоставления последовательностей байт символам языка. Существует множество различных кодировок для разных языков. Определить кодировку текстового файла можно при помощи ряда программных средств.
Вам понадобится
- — Microsoft Office Word;
- — KWrite;
- — Mozilla Firefox;
- — enca.
Инструкция
Используйте редактор Microsoft Office Word, если он установлен на компьютере, для определения кодировки текстового файла. Запустите данное приложение. В главном меню последовательно выберите пункты «Файл» и «Открыть…» или нажмите сочетание клавиш Ctrl+O. В отобразившемся диалоге перейдите к нужному каталогу и выделите файл. Нажмите кнопку «Открыть». Если кодировка текста отличается от CP1251, автоматически откроется диалог «Преобразование файла». Активируйте в нем опцию «Другая» и подберите кодировку, используя список, находящийся справа. При выборе правильной кодировки в поле «Образец» будет выведен читаемый текст.
Примените текстовые редакторы, допускающие выбор кодировки текста источника. Хорошим примером подобного приложения является KWrite (работает в среде KDE в UNIX-подобных системах). Загрузите текстовый файл в редактор. Затем просто перебирайте кодировки, пока не отобразится читаемый текст (в KWrite для этого используется раздел Encoding меню Tools).
Аналогично текстовому редактору для определения кодировки файла можно использовать и браузер. Воспользуйтесь Mozilla Firefox. Запустите данное приложение. Если оно не установлено, загрузите подходящий дистрибутив с сайта mozilla.org и инсталлируйте его. Откройте в браузере текстовый файл. Для этого выберите в главном меню пункты «Файл» и «Открыть файл…» или нажмите Ctrl+O. Если загруженный текст отобразился корректно, разверните раздел «Кодировка» меню «Вид» и узнайте кодировку из названия пункта, на котором установлена отметка. В противном случае подберите данный параметр путем выбора различных пунктов того же меню, а также его раздела «Дополнительные».
Примените специализированные утилиты для определения кодировок текстовых файлов. В UNIX-подобных системах можно использовать enca. При необходимости установите эту программу при помощи доступных менеджеров пакетов. Выведите список доступных языков, выполнив команду:
enca —list languages
Определите кодировку текстового файла, указав его имя при помощи опции -g и язык документа при помощи опции -L. Например:
enca -L russian -g /home/vic/tmp/aaa.txt.
Источники:
- Кодировка текста ASCII
Войти на сайт
или
Забыли пароль?
Еще не зарегистрированы?
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
Программный комплекс SocialKit корректно работает с кириллицей в текстовых файлах, кодировка которых соответствует стандарту Windows-1251 (кратко может быть записано как CP1251 или ANSI). В этой связи в задачах, поддерживающих указание внешнего файла с перечнем комментариев, сообщений, описаний и прочей информации, которая может содержать кириллицу, нужно указывать текстовые файлы, где русский текст задан в кодировке по стандарту Windows-1251 или же просто ANSI, или CP1251 — всё это, по сути, одно и то же.
Учитывая, что многие инструменты по работе с текстом не отображают, в какой именно кодировке задан текст в текстовом файле и/или не поддерживают преобразование кодировок, то у новичков часто возникает вопрос о том, как именно привести кодировку текстового файла с русским текстом к понятному для SocialKit формату CP1251.
Следует сразу отметить, что большинство текстовых редакторов для ОС Windows (например, встроенный Блокнот и Wordpad) по умолчанию создают текстовые файлы именно с кодировкой по стандарту Windows-1251. Однако, эта кодировка по умолчанию может быть изменена в следствие тех или иных действий.
Если вы не уверены в том, в какой именно кодировке задан текст, то проще всего этот текст пересохранить через стандартный Блокнот Windows. При пересохранении Блокнот также покажет, в каком формате текст сейчас.
Опишем эту простую процедуру по шагам.
1. Открыть искомый текстовый файл в Блокноте Windows и выбрать пункт меню «Файл» -> «Сохранить как…».
Пример текстового файла, в котором русский текст задан в формате UTF, но это не очевидно при открытии.
2. В открывшемся диалоговом окне вы сразу видите, в какой кодировке был сохранён текст в текстовом файле.
Диалоговое окно пересохранения текстового файла, в котором можно сразу изменить кодировку.
Как видно, в примере текст в текстовом файле был ранее сохранён в кодировке UTF-8. Для изменения кодировке достаточно выбрать в выпадающем списке кодировку ANSI и нажать кнопку «Сохранить«.
При этом зрительно для вас ничего не изменится, но многое изменится для программы и алгоритмов, занимающихся обработкой текста в процессе отправки. Корректно Instagram’у будет отправлен только ANSI-текст.
This isn’t really a programming question, is there a command line or Windows tool (Windows 7) to get the current encoding of a text file? Sure I can write a little C# app but I wanted to know if there is something already built in?
Ross Ridge
37.8k7 gold badges79 silver badges111 bronze badges
asked Sep 14, 2010 at 15:28
3
Open up your file using regular old vanilla Notepad that comes with Windows.
It will show you the encoding of the file when you click «Save As…«.
It’ll look like this:
Whatever the default-selected encoding is, that is what your current encoding is for the file.
If it is UTF-8, you can change it to ANSI and click save to change the encoding (or visa-versa).
I realize there are many different types of encoding, but this was all I needed when I was informed our export files were in UTF-8 and they required ANSI. It was a onetime export, so Notepad fit the bill for me.
FYI: From my understanding I think «Unicode» (as listed in Notepad) is a misnomer for UTF-16.
More here on Notepad’s «Unicode» option: Windows 7 — UTF-8 and Unicdoe
answered Nov 20, 2012 at 0:27
MikeTeeVeeMikeTeeVee
18k7 gold badges76 silver badges70 bronze badges
14
If you have «git» or «Cygwin» on your Windows Machine, then go to the folder where your file is present and execute the command:
file *
This will give you the encoding details of all the files in that folder.
answered Apr 19, 2017 at 7:37
George NinanGeorge Ninan
1,9092 gold badges12 silver badges8 bronze badges
4
The (Linux) command-line tool ‘file’ is available on Windows via GnuWin32:
http://gnuwin32.sourceforge.net/packages/file.htm
If you have git installed, it’s located in C:Program Filesgitusrbin.
Example:
C:UsersSHDownloadsSquareRoot>file * _UpgradeReport_Files; directory Debug; directory duration.h; ASCII C++ program text, with CRLF line terminators ipch; directory main.cpp; ASCII C program text, with CRLF line terminators Precision.txt; ASCII text, with CRLF line terminators Release; directory Speed.txt; ASCII text, with CRLF line terminators SquareRoot.sdf; data SquareRoot.sln; UTF-8 Unicode (with BOM) text, with CRLF line terminators SquareRoot.sln.docstates.suo; PCX ver. 2.5 image data SquareRoot.suo; CDF V2 Document, corrupt: Cannot read summary info SquareRoot.vcproj; XML document text SquareRoot.vcxproj; XML document text SquareRoot.vcxproj.filters; XML document text SquareRoot.vcxproj.user; XML document text squarerootmethods.h; ASCII C program text, with CRLF line terminators UpgradeLog.XML; XML document text C:UsersSHDownloadsSquareRoot>file --mime-encoding * _UpgradeReport_Files; binary Debug; binary duration.h; us-ascii ipch; binary main.cpp; us-ascii Precision.txt; us-ascii Release; binary Speed.txt; us-ascii SquareRoot.sdf; binary SquareRoot.sln; utf-8 SquareRoot.sln.docstates.suo; binary SquareRoot.suo; CDF V2 Document, corrupt: Cannot read summary infobinary SquareRoot.vcproj; us-ascii SquareRoot.vcxproj; utf-8 SquareRoot.vcxproj.filters; utf-8 SquareRoot.vcxproj.user; utf-8 squarerootmethods.h; us-ascii UpgradeLog.XML; us-ascii
Ed S.
121k21 gold badges181 silver badges262 bronze badges
answered Jan 13, 2016 at 11:58
SybrenSybren
8716 silver badges5 bronze badges
7
Install git ( on Windows you have to use git bash console). Type:
file --mime-encoding *
for all files in the current directory , or
file --mime-encoding */*
for the files in all subdirectories
Ross Rogers
23.1k26 gold badges107 silver badges163 bronze badges
answered Nov 15, 2019 at 14:57
phd_coderphd_coder
3613 silver badges3 bronze badges
1
Here’s my take how to detect the Unicode family of text encodings via BOM. The accuracy of this method is low, as this method only works on text files (specifically Unicode files), and defaults to ascii
when no BOM is present (like most text editors, the default would be UTF8
if you want to match the HTTP/web ecosystem).
Update 2018: I no longer recommend this method. I recommend using file.exe from GIT or *nix tools as recommended by @Sybren, and I show how to do that via PowerShell in a later answer.
# from https://gist.github.com/zommarin/1480974
function Get-FileEncoding($Path) {
$bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)
if(!$bytes) { return 'utf8' }
switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
'^efbbbf' { return 'utf8' }
'^2b2f76' { return 'utf7' }
'^fffe' { return 'unicode' }
'^feff' { return 'bigendianunicode' }
'^0000feff' { return 'utf32' }
default { return 'ascii' }
}
}
dir ~DocumentsWindowsPowershell -File |
select Name,@{Name='Encoding';Expression={Get-FileEncoding $_.FullName}} |
ft -AutoSize
Recommendation: This can work reasonably well if the dir
, ls
, or Get-ChildItem
only checks known text files, and when you’re only looking for «bad encodings» from a known list of tools. (i.e. SQL Management Studio defaults to UTF16, which broke GIT auto-cr-lf for Windows, which was the default for many years.)
answered Jan 22, 2015 at 0:02
yzorgyzorg
4,1163 gold badges39 silver badges56 bronze badges
8
A simple solution might be opening the file in Firefox.
- Drag and drop the file into firefox
- Press Ctrl+I to open the page info
and the text encoding will appear on the «Page Info» window.
Note: If the file is not in txt format, just rename it to txt and try again.
P.S. For more info see this article.
answered Aug 8, 2019 at 17:37
Just ShadowJust Shadow
10.1k5 gold badges55 silver badges69 bronze badges
1
I wrote the #4 answer (at time of writing). But lately I have git installed on all my computers, so now I use @Sybren’s solution. Here is a new answer that makes that solution handy from powershell (without putting all of git/usr/bin in the PATH, which is too much clutter for me).
Add this to your profile.ps1
:
$global:gitbin = 'C:Program FilesGitusrbin'
Set-Alias file.exe $gitbinfile.exe
And used like: file.exe --mime-encoding *
. You must include .exe in the command for PS alias to work.
But if you don’t customize your PowerShell profile.ps1 I suggest you start with mine: https://gist.github.com/yzorg/8215221/8e38fd722a3dfc526bbe4668d1f3b08eb7c08be0
and save it to ~DocumentsWindowsPowerShell
. It’s safe to use on a computer without git, but will write warnings when git is not found.
The .exe in the command is also how I use C:WINDOWSsystem32where.exe
from powershell; and many other OS CLI commands that are «hidden by default» by powershell, *shrug*.
answered Oct 18, 2017 at 17:36
yzorgyzorg
4,1163 gold badges39 silver badges56 bronze badges
4
you can simply check that by opening your git bash on the file location then running the command file -i file_name
example
user filesData
$ file -i data.csv
data.csv: text/csv; charset=utf-8
answered Feb 23, 2022 at 14:04
DINA TAKLITDINA TAKLIT
5,8829 gold badges61 silver badges72 bronze badges
Some C code here for reliable ascii, bom’s, and utf8 detection: https://unicodebook.readthedocs.io/guess_encoding.html
Only ASCII, UTF-8 and encodings using a BOM (UTF-7 with BOM, UTF-8 with BOM,
UTF-16, and UTF-32) have reliable algorithms to get the encoding of a document.
For all other encodings, you have to trust heuristics based on statistics.
EDIT:
A powershell version of a C# answer from: Effective way to find any file’s Encoding. Only works with signatures (boms).
# get-encoding.ps1
param([Parameter(ValueFromPipeline=$True)] $filename)
begin {
# set .net current directoy
[Environment]::CurrentDirectory = (pwd).path
}
process {
$reader = [System.IO.StreamReader]::new($filename,
[System.Text.Encoding]::default,$true)
$peek = $reader.Peek()
$encoding = $reader.currentencoding
$reader.close()
[pscustomobject]@{Name=split-path $filename -leaf
BodyName=$encoding.BodyName
EncodingName=$encoding.EncodingName}
}
.get-encoding chinese8.txt
Name BodyName EncodingName
---- -------- ------------
chinese8.txt utf-8 Unicode (UTF-8)
get-childitem -file | .get-encoding
answered Nov 8, 2018 at 17:43
js2010js2010
21.1k4 gold badges56 silver badges60 bronze badges
1
Looking for a Node.js/npm solution? Try encoding-checker:
npm install -g encoding-checker
Usage
Usage: encoding-checker [-p pattern] [-i encoding] [-v]
Options:
--help Show help [boolean]
--version Show version number [boolean]
--pattern, -p, -d [default: "*"]
--ignore-encoding, -i [default: ""]
--verbose, -v [default: false]
Examples
Get encoding of all files in current directory:
encoding-checker
Return encoding of all md
files in current directory:
encoding-checker -p "*.md"
Get encoding of all files in current directory and its subfolders (will take quite some time for huge folders; seemingly unresponsive):
encoding-checker -p "**"
For more examples refer to the npm docu or the official repository.
answered Jan 27, 2021 at 21:22
ToJoToJo
1,2291 gold badge14 silver badges24 bronze badges
0
Similar to the solution listed above with Notepad, you can also open the file in Visual Studio, if you’re using that. In Visual Studio, you can select «File > Advanced Save Options…»
The «Encoding:» combo box will tell you specifically which encoding is currently being used for the file. It has a lot more text encodings listed in there than Notepad does, so it’s useful when dealing with various files from around the world and whatever else.
Just like Notepad, you can also change the encoding from the list of options there, and then saving the file after hitting «OK». You can also select the encoding you want through the «Save with Encoding…» option in the Save As dialog (by clicking the arrow next to the Save button).
answered Oct 11, 2016 at 18:57
JaykeBirdJaykeBird
3756 silver badges16 bronze badges
2
The only way that I have found to do this is VIM or Notepad++.
answered Sep 14, 2017 at 15:49
Todd PartridgeTodd Partridge
6331 gold badge8 silver badges10 bronze badges
1
EncodingChecker
File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.
File Encoding Checker requires .NET 4 or above to run.
answered Jul 8, 2020 at 16:29
Amr AliAmr Ali
2,6121 gold badge16 silver badges11 bronze badges
This isn’t really a programming question, is there a command line or Windows tool (Windows 7) to get the current encoding of a text file? Sure I can write a little C# app but I wanted to know if there is something already built in?
Ross Ridge
37.8k7 gold badges79 silver badges111 bronze badges
asked Sep 14, 2010 at 15:28
3
Open up your file using regular old vanilla Notepad that comes with Windows.
It will show you the encoding of the file when you click «Save As…«.
It’ll look like this:
Whatever the default-selected encoding is, that is what your current encoding is for the file.
If it is UTF-8, you can change it to ANSI and click save to change the encoding (or visa-versa).
I realize there are many different types of encoding, but this was all I needed when I was informed our export files were in UTF-8 and they required ANSI. It was a onetime export, so Notepad fit the bill for me.
FYI: From my understanding I think «Unicode» (as listed in Notepad) is a misnomer for UTF-16.
More here on Notepad’s «Unicode» option: Windows 7 — UTF-8 and Unicdoe
answered Nov 20, 2012 at 0:27
MikeTeeVeeMikeTeeVee
18k7 gold badges76 silver badges70 bronze badges
14
If you have «git» or «Cygwin» on your Windows Machine, then go to the folder where your file is present and execute the command:
file *
This will give you the encoding details of all the files in that folder.
answered Apr 19, 2017 at 7:37
George NinanGeorge Ninan
1,9092 gold badges12 silver badges8 bronze badges
4
The (Linux) command-line tool ‘file’ is available on Windows via GnuWin32:
http://gnuwin32.sourceforge.net/packages/file.htm
If you have git installed, it’s located in C:Program Filesgitusrbin.
Example:
C:UsersSHDownloadsSquareRoot>file * _UpgradeReport_Files; directory Debug; directory duration.h; ASCII C++ program text, with CRLF line terminators ipch; directory main.cpp; ASCII C program text, with CRLF line terminators Precision.txt; ASCII text, with CRLF line terminators Release; directory Speed.txt; ASCII text, with CRLF line terminators SquareRoot.sdf; data SquareRoot.sln; UTF-8 Unicode (with BOM) text, with CRLF line terminators SquareRoot.sln.docstates.suo; PCX ver. 2.5 image data SquareRoot.suo; CDF V2 Document, corrupt: Cannot read summary info SquareRoot.vcproj; XML document text SquareRoot.vcxproj; XML document text SquareRoot.vcxproj.filters; XML document text SquareRoot.vcxproj.user; XML document text squarerootmethods.h; ASCII C program text, with CRLF line terminators UpgradeLog.XML; XML document text C:UsersSHDownloadsSquareRoot>file --mime-encoding * _UpgradeReport_Files; binary Debug; binary duration.h; us-ascii ipch; binary main.cpp; us-ascii Precision.txt; us-ascii Release; binary Speed.txt; us-ascii SquareRoot.sdf; binary SquareRoot.sln; utf-8 SquareRoot.sln.docstates.suo; binary SquareRoot.suo; CDF V2 Document, corrupt: Cannot read summary infobinary SquareRoot.vcproj; us-ascii SquareRoot.vcxproj; utf-8 SquareRoot.vcxproj.filters; utf-8 SquareRoot.vcxproj.user; utf-8 squarerootmethods.h; us-ascii UpgradeLog.XML; us-ascii
Ed S.
121k21 gold badges181 silver badges262 bronze badges
answered Jan 13, 2016 at 11:58
SybrenSybren
8716 silver badges5 bronze badges
7
Install git ( on Windows you have to use git bash console). Type:
file --mime-encoding *
for all files in the current directory , or
file --mime-encoding */*
for the files in all subdirectories
Ross Rogers
23.1k26 gold badges107 silver badges163 bronze badges
answered Nov 15, 2019 at 14:57
phd_coderphd_coder
3613 silver badges3 bronze badges
1
Here’s my take how to detect the Unicode family of text encodings via BOM. The accuracy of this method is low, as this method only works on text files (specifically Unicode files), and defaults to ascii
when no BOM is present (like most text editors, the default would be UTF8
if you want to match the HTTP/web ecosystem).
Update 2018: I no longer recommend this method. I recommend using file.exe from GIT or *nix tools as recommended by @Sybren, and I show how to do that via PowerShell in a later answer.
# from https://gist.github.com/zommarin/1480974
function Get-FileEncoding($Path) {
$bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4)
if(!$bytes) { return 'utf8' }
switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) {
'^efbbbf' { return 'utf8' }
'^2b2f76' { return 'utf7' }
'^fffe' { return 'unicode' }
'^feff' { return 'bigendianunicode' }
'^0000feff' { return 'utf32' }
default { return 'ascii' }
}
}
dir ~DocumentsWindowsPowershell -File |
select Name,@{Name='Encoding';Expression={Get-FileEncoding $_.FullName}} |
ft -AutoSize
Recommendation: This can work reasonably well if the dir
, ls
, or Get-ChildItem
only checks known text files, and when you’re only looking for «bad encodings» from a known list of tools. (i.e. SQL Management Studio defaults to UTF16, which broke GIT auto-cr-lf for Windows, which was the default for many years.)
answered Jan 22, 2015 at 0:02
yzorgyzorg
4,1163 gold badges39 silver badges56 bronze badges
8
A simple solution might be opening the file in Firefox.
- Drag and drop the file into firefox
- Press Ctrl+I to open the page info
and the text encoding will appear on the «Page Info» window.
Note: If the file is not in txt format, just rename it to txt and try again.
P.S. For more info see this article.
answered Aug 8, 2019 at 17:37
Just ShadowJust Shadow
10.1k5 gold badges55 silver badges69 bronze badges
1
I wrote the #4 answer (at time of writing). But lately I have git installed on all my computers, so now I use @Sybren’s solution. Here is a new answer that makes that solution handy from powershell (without putting all of git/usr/bin in the PATH, which is too much clutter for me).
Add this to your profile.ps1
:
$global:gitbin = 'C:Program FilesGitusrbin'
Set-Alias file.exe $gitbinfile.exe
And used like: file.exe --mime-encoding *
. You must include .exe in the command for PS alias to work.
But if you don’t customize your PowerShell profile.ps1 I suggest you start with mine: https://gist.github.com/yzorg/8215221/8e38fd722a3dfc526bbe4668d1f3b08eb7c08be0
and save it to ~DocumentsWindowsPowerShell
. It’s safe to use on a computer without git, but will write warnings when git is not found.
The .exe in the command is also how I use C:WINDOWSsystem32where.exe
from powershell; and many other OS CLI commands that are «hidden by default» by powershell, *shrug*.
answered Oct 18, 2017 at 17:36
yzorgyzorg
4,1163 gold badges39 silver badges56 bronze badges
4
you can simply check that by opening your git bash on the file location then running the command file -i file_name
example
user filesData
$ file -i data.csv
data.csv: text/csv; charset=utf-8
answered Feb 23, 2022 at 14:04
DINA TAKLITDINA TAKLIT
5,8829 gold badges61 silver badges72 bronze badges
Some C code here for reliable ascii, bom’s, and utf8 detection: https://unicodebook.readthedocs.io/guess_encoding.html
Only ASCII, UTF-8 and encodings using a BOM (UTF-7 with BOM, UTF-8 with BOM,
UTF-16, and UTF-32) have reliable algorithms to get the encoding of a document.
For all other encodings, you have to trust heuristics based on statistics.
EDIT:
A powershell version of a C# answer from: Effective way to find any file’s Encoding. Only works with signatures (boms).
# get-encoding.ps1
param([Parameter(ValueFromPipeline=$True)] $filename)
begin {
# set .net current directoy
[Environment]::CurrentDirectory = (pwd).path
}
process {
$reader = [System.IO.StreamReader]::new($filename,
[System.Text.Encoding]::default,$true)
$peek = $reader.Peek()
$encoding = $reader.currentencoding
$reader.close()
[pscustomobject]@{Name=split-path $filename -leaf
BodyName=$encoding.BodyName
EncodingName=$encoding.EncodingName}
}
.get-encoding chinese8.txt
Name BodyName EncodingName
---- -------- ------------
chinese8.txt utf-8 Unicode (UTF-8)
get-childitem -file | .get-encoding
answered Nov 8, 2018 at 17:43
js2010js2010
21.1k4 gold badges56 silver badges60 bronze badges
1
Looking for a Node.js/npm solution? Try encoding-checker:
npm install -g encoding-checker
Usage
Usage: encoding-checker [-p pattern] [-i encoding] [-v]
Options:
--help Show help [boolean]
--version Show version number [boolean]
--pattern, -p, -d [default: "*"]
--ignore-encoding, -i [default: ""]
--verbose, -v [default: false]
Examples
Get encoding of all files in current directory:
encoding-checker
Return encoding of all md
files in current directory:
encoding-checker -p "*.md"
Get encoding of all files in current directory and its subfolders (will take quite some time for huge folders; seemingly unresponsive):
encoding-checker -p "**"
For more examples refer to the npm docu or the official repository.
answered Jan 27, 2021 at 21:22
ToJoToJo
1,2291 gold badge14 silver badges24 bronze badges
0
Similar to the solution listed above with Notepad, you can also open the file in Visual Studio, if you’re using that. In Visual Studio, you can select «File > Advanced Save Options…»
The «Encoding:» combo box will tell you specifically which encoding is currently being used for the file. It has a lot more text encodings listed in there than Notepad does, so it’s useful when dealing with various files from around the world and whatever else.
Just like Notepad, you can also change the encoding from the list of options there, and then saving the file after hitting «OK». You can also select the encoding you want through the «Save with Encoding…» option in the Save As dialog (by clicking the arrow next to the Save button).
answered Oct 11, 2016 at 18:57
JaykeBirdJaykeBird
3756 silver badges16 bronze badges
2
The only way that I have found to do this is VIM or Notepad++.
answered Sep 14, 2017 at 15:49
Todd PartridgeTodd Partridge
6331 gold badge8 silver badges10 bronze badges
1
EncodingChecker
File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.
File Encoding Checker requires .NET 4 or above to run.
answered Jul 8, 2020 at 16:29
Amr AliAmr Ali
2,6121 gold badge16 silver badges11 bronze badges
0 / 0 / 0
Регистрация: 15.07.2019
Сообщений: 22
1
13.05.2020, 01:25. Показов 3261. Ответов 29
есть файлы
1.txt
2.txt
3.txt
4.txt
5.txt
нужно из батника (cmd) узнать какая кодировка у каждого файла.
возможные варианты кодировок:
(«ansi», «utf8», «unicode»)
идеально получить значение в переменную.
можна юзать стандартные команды виндовс (cmd) и PS
Windows Batch file | ||
|
где-то так…
но понять как можна получить кодировку ДРУГОГО файла а не поточного батника -найти не смог (((
Добавлено через 29 минут
незнаю на чем ЭТО,
но может как-то можна «сварганить» что-то подобное на баш/пш ???
Код
public static class StreamExtension { /// <summary> /// Convert the content to a string. /// </summary> /// <param name="stream">The stream.</param> /// <returns></returns> public static string ReadAsString(this Stream stream) { var startPosition = stream.Position; try { // 1. Check for a BOM // 2. or try with UTF-8. The most (86.3%) used encoding. Visit: http://w3techs.com/technologies/overview/character_encoding/all/ var streamReader = new StreamReader(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: true); return streamReader.ReadToEnd(); } catch (DecoderFallbackException ex) { stream.Position = startPosition; // 3. The second most (6.7%) used encoding is ISO-8859-1. So use Windows-1252 (0.9%, also know as ANSI), which is a superset of ISO-8859-1. var streamReader = new StreamReader(stream, Encoding.GetEncoding(1252)); return streamReader.ReadToEnd(); } } }
Добавлено через 11 минут
нашел еще на просторах стекОверфлов,
но непонятно будет ли кирилицу хавать….
Bash | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
Как определить кодировку файла?
В моей файловой системе (Windows 7) у меня есть несколько текстовых файлов (это файлы сценариев SQL, если это имеет значение).
При открытии с помощью Notepad ++ в меню «Кодировка» сообщается, что некоторые из них имеют кодировку «UCS-2 Little Endian», а некоторые — «UTF-8 без BOM».
В чем здесь разница? Все они кажутся совершенно правильными сценариями. Как я могу сказать, какие кодировки у файла без Notepad ++?
Ответы:
Файлы обычно указывают свою кодировку с заголовком файла. Есть много примеров здесь . Однако даже читая заголовок, вы никогда не можете быть уверены, какую кодировку файл действительно использует .
Например, файл с первыми тремя байтами 0xEF,0xBB,0xBF
, вероятно , является файлом в кодировке UTF-8. Однако это может быть файл ISO-8859-1, который начинается с символов 
. Или это может быть совершенно другой тип файла.
Notepad ++ делает все возможное, чтобы угадать, какую кодировку использует файл, и в большинстве случаев он делает это правильно. Хотя иногда это не так — поэтому меню «Кодировка» есть, поэтому вы можете отменить его лучшее предположение.
Для двух кодировок вы упоминаете:
- Файлы «Little Endian UCS-2» — это файлы UTF-16 (основанные на том, что я понимаю из информации здесь ), поэтому, вероятно, начнем с
0xFF,0xFE
первых 2 байтов. Из того, что я могу сказать, Notepad ++ описывает их как «UCS-2», поскольку он не поддерживает определенные аспекты UTF-16. - Файлы «UTF-8 без BOM» не имеют байтов заголовков. Вот что означает бит «без спецификации».
Тебе нельзя. Если бы вы могли это сделать, не было бы так много веб-сайтов или текстовых файлов со «случайным бредом». Вот почему кодирование обычно отправляется вместе с полезной нагрузкой в виде метаданных.
В противном случае все, что вы можете сделать, — это «умное предположение», но результат часто неоднозначен, поскольку одна и та же последовательность байтов может быть допустимой в нескольких кодировках.
Способ 1: 2cyr
Основное предназначение онлайн-сервиса 2cyr заключается в декодировании определенного отрывка текста, однако это не помешает использовать встроенные в него инструменты для определения кодировки, для чего потребуется только скопировать небольшую надпись.
Перейти к онлайн-сервису 2cyr
- В самом декодере вставьте скопированный текст в соответствующую форму, используя контекстное меню или горячую клавишу Ctrl + V.
- Убедитесь в том, что текст был успешно добавлен, а затем в поле «Выберите кодировку» установите значение «Автоматически (рекомендуется)». Подтвердите распознавание, нажав по кнопке «ОК», которая расположена справа.
- Остается только ознакомиться с названием кодировки в поле «Отображается как», чтобы узнать ее.
- Дополнительно вы можете посмотреть перевод ее в читаемый вид, если та нечитабельна, а также узнать, какая кодировка использовалась для этого.
- В 2cyr есть и другие читаемые варианты, которые можно использовать в своих целях, переключаясь между ними в соответствующих всплывающих меню.
Ничего не помешает сохранить или запомнить этот онлайн-сервис и обращаться к нему в те моменты, когда требуется перевести кодировку или снова определить ее. Если же этот вариант не подходит, переходите к рассмотрению следующих сайтов.
Способ 2: Online Decoder
Онлайн-сервис под названием Online Decoder тоже умеет определять кодировку текста в автоматическом режиме, а также переводить ее в читаемый вид или любые другие кодировки, если это требуется. Подбор символов на этом сайте осуществляется буквально в несколько кликов.
Перейти к онлайн-сервису Online Decoder
- Воспользуйтесь ссылкой выше или самостоятельно откройте главную страницу сайта Online Decoder, где сразу же активируйте поле для ввода и вставьте туда целевой текст.
- Напротив пункта «Раскодировать текст автоматически (рекомендуется)» нажмите по кнопке «Подбор» для запуска процесса распознавания.
- Та кодировка, в которую выполнен перевод, отображается второй.
- Исходная находится прямо после надписи «Я знаю нужные кодировки». Ее и надо узнать, если речь идет об определении стилистики символов.
- Перевод в выбранную конечную кодировку вы видите внизу, можете его изменить или скопировать.
- Используйте дополнительные инструменты сайта Online Decoder, если нужно продолжить взаимодействие с другими надписями.
Способ 3: FoxTools
FoxTools — еще один онлайн-сервис, основное предназначение которого заключается в декодировании текста, однако его функциональность можно использовать и для определения необходимого символьного набора, что происходит так:
Перейти к онлайн-сервису FoxTools
- Активируйте поле для ввода и вставьте туда скопированную ранее надпись.
- Снизу поля «Исходная кодировка» вы найдете кнопку «Определить», по которой и следует нажать для запуска процесса распознавания.
- Если параллельно осуществляется перевод в читаемый вид, выберите его из выпадающего меню сверху.
- Нажмите «Отправить», чтобы получить результат со всей необходимой информацией.
- Ознакомьтесь с параметром возле пункта «Исходная кодировка» для определения символьного набора. Если он отображен не в кодовом названии, найдите перевод через Википедию для общего понимания.
- Иногда FoxTools не распознает редко используемые кодировки, поэтому потребуется переключиться в режим «Все кодировки» и повторить процедуру подбора.
Еще статьи по данной теме: